package im.starchat.chat.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.squareup.picasso.Picasso;
import com.tencent.TIMCallBack;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMElemType;
import com.tencent.TIMGroupManager;
import com.tencent.TIMGroupSystemElem;
import com.tencent.TIMGroupSystemElemType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;
import com.tencent.TIMTextElem;
import com.tencent.TIMValueCallBack;
import com.tencent.av.TIMAvManager;
import com.tencent.av.sdk.AVAudioCtrl;
import com.tencent.av.sdk.AVConstants;
import com.tencent.av.sdk.AVEndpoint;
import com.tencent.av.sdk.AVError;
import com.tencent.av.sdk.AVRoomMulti;
import com.tencent.av.sdk.AVView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.profile.ContributionActivity;
import im.starchat.chat.activity.profile.MyDiamondActivity;
import im.starchat.chat.activity.publish.GameOverActivity;
import im.starchat.chat.adapter.AvChatAdapter;
import im.starchat.chat.adapter.ChatMsgListAdapter;
import im.starchat.chat.adapter.GiftAdapter;
import im.starchat.chat.control.QavsdkControl;
import im.starchat.chat.dialog.CommentDialogFragment;
import im.starchat.chat.dialog.HostDialogFragment;
import im.starchat.chat.dialog.MemberDialogFragment;
import im.starchat.chat.dialog.RechargeFragment;
import im.starchat.chat.dialog.ShareRoomDialogFragment;
import im.starchat.chat.rest.model.ChatEntity;
import im.starchat.chat.rest.model.CommentBean;
import im.starchat.chat.rest.model.GiftBean;
import im.starchat.chat.rest.model.MemberInfo;
import im.starchat.chat.rest.model.RoomBean;
import im.starchat.chat.rest.model.TIMGiftModel;
import im.starchat.chat.rest.model.UserBean;
import im.starchat.chat.rest.model.api.NullResponse;
import im.starchat.chat.rest.model.api.ZhiboUserListResponse;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.GsonUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.utils.Util;
import im.starchat.chat.view.CircularImageButton;
import im.starchat.chat.view.DanMuView;
import im.starchat.chat.view.GiftViewHolder;
import im.starchat.chat.view.HorizontalListView;
import me.yifeiyuan.library.PeriscopeLayout;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * 直播界面
 */
public class AvActivity extends BaseActivity implements View.OnClickListener {


    private ArrayList<GiftBean> mGiftBeanList;
    private static final String TAG = "AvActivity";
    private static final String UNREAD = "0";
    private static final int PRIASE_MSG = 1;
    private static final int MEMBER_ENTER_MSG = 2;
    private static final int MEMBER_EXIT_MSG = 3;
    //    private static final int VIDEOCHAT_INVITE = 4;
//    private static final int YES_I_JOIN = 5;
    private static final int NO_I_REFUSE = 6;
    private static final int MUTEVOICE = 7;
    private static final int UNMUTEVOICE = 8;
    private static final int MUTEVIDEO = 9;
    private static final int UNMUTEVIDEO = 10;
    private static final int CLOSEVIDEOSEND = 11;
    private static final int GIFT_SEND = 12;
    private static final int BARRAGE_SEND = 13;

    private static final int DIALOG_INIT = 0;
    private static final int DIALOG_AT_ON_CAMERA = DIALOG_INIT + 1;
    private static final int DIALOG_ON_CAMERA_FAILED = DIALOG_AT_ON_CAMERA + 1;
    private static final int DIALOG_AT_OFF_CAMERA = DIALOG_ON_CAMERA_FAILED + 1;
    private static final int DIALOG_OFF_CAMERA_FAILED = DIALOG_AT_OFF_CAMERA + 1;
    private static final int DIALOG_AT_SWITCH_FRONT_CAMERA = DIALOG_OFF_CAMERA_FAILED + 1;
    private static final int DIALOG_SWITCH_FRONT_CAMERA_FAILED = DIALOG_AT_SWITCH_FRONT_CAMERA + 1;
    private static final int DIALOG_AT_SWITCH_BACK_CAMERA = DIALOG_SWITCH_FRONT_CAMERA_FAILED + 1;
    private static final int DIALOG_SWITCH_BACK_CAMERA_FAILED = DIALOG_AT_SWITCH_BACK_CAMERA + 1;
    private static final int DIALOG_DESTROY = DIALOG_SWITCH_BACK_CAMERA_FAILED + 1;

    private static final int ERROR_MESSAGE_TOO_LONG = 0x1;
    private static final int ERROR_ACCOUNT_NOT_EXIT = ERROR_MESSAGE_TOO_LONG + 1;

    private static final int REFRESH_CHAT = 0x100;
    private static final int UPDAT_WALL_TIME_TIMER_TASK = REFRESH_CHAT + 1;
    private static final int REMOVE_CHAT_ITEM_TIMER_TASK = UPDAT_WALL_TIME_TIMER_TASK + 1;
    private static final int UPDAT_MEMBER = REMOVE_CHAT_ITEM_TIMER_TASK + 1;
    private static final int MEMBER_EXIT_COMPLETE = UPDAT_MEMBER + 1;
    private static final int CLOSE_VIDEO = MEMBER_EXIT_COMPLETE + 1;
    private static final int START_RECORD = CLOSE_VIDEO + 1;
    private static final int IM_HOST_LEAVE = START_RECORD + 1;
    private static final int GET_ROOM_INFO = IM_HOST_LEAVE + 1;
    private static final int REFRESH_PRAISE = GET_ROOM_INFO + 1;
    private static final int SHOW_GIFT = REFRESH_PRAISE + 1;
    private static final int GIFTLIST_1_DISMISS = SHOW_GIFT + 1;
    private static final int GIFTLIST_2_DISMISS = GIFTLIST_1_DISMISS + 1;

    private boolean mIsPaused = false;
    private boolean mIsClicked = false;
    private boolean mIsSuccess = false;
    private boolean mRecord = false;
    private int mOnOffCameraErrorCode = AVError.AV_OK;
    private int mSwitchCameraErrorCode = AVError.AV_OK;

    private ProgressDialog mDialogInit = null;
    private ProgressDialog mDialogAtOnCamera = null;
    private ProgressDialog mDialogAtOffCamera = null;
    private ProgressDialog mDialogAtSwitchFrontCamera = null;
    private ProgressDialog mDialogAtSwitchBackCamera = null;
    private ProgressDialog mDialogAtDestroy = null;
    private String videoRecordId = "";
    private ListView mListViewMsgItems;
    private EditText mEditTextInputMsg;
    private Button mButtonSendMsg;
    private InputMethodManager mInputKeyBoard;
    private TIMConversation mConversation;//获取群聊会话
    private TIMConversation mSystemConversation;//, testConversation;
    private List<ChatEntity> mArrayListChatEntity;
    private ChatMsgListAdapter mChatMsgListAdapter;
    private final int MAX_PAGE_NUM = 10;
    private int mLoadMsgNum = MAX_PAGE_NUM;
    private boolean bNeverLoadMore = true;
    private boolean bMore = true;
    private boolean mIsLoading = false;
    private boolean FormalEnv = true;
    private QavsdkControl mQavsdkControl;
    private String mRecvIdentifier = "";
    private String mHostIdentifier = "";
    OrientationEventListener mOrientationEventListener = null;
    int mRotationAngle = 0;
    private PowerManager.WakeLock wakeLock;
    private Context ctx;
    //    private UserInfo mSelfUserInfo;
    private int roomNum;
    private String groupId;//群id
    private boolean mChecked = false;
    private int StreamType = 2;
    private int StreamTypeCode = Constants.HLS;
    private Dialog mVideoMemberInfoDialog;

    private HashMap<String, String> mUserNameMap = new HashMap<>();
    ArrayList<MemberInfo> mMemberList, mNormalMemberList;

    HashMap<String, MemberInfo> shownUserMap = new HashMap<>();
    HashMap<String, MemberInfo> unShownUserMap = new HashMap<>();
    //    private GridView mGridView;
    private static final int slength = 40;
    private float density;
    private XLApplication mQavsdkApplication;
    private int groupForPush;
    private int praiseNum;

    private ImageView mButtonPraise;
    private TextView mClockTextView;
    private long second = 0;
    private long time;
    //    private int mMemberVideoCount = 0;
    private AVView mRequestViewList[] = null;
    private String mRequestIdentifierList[] = null;
    private int stop = 1;
    private Timer mVideoTimer;
    private Timer mChatTimer;
    private Timer mHeartClickTimer;
    private VideoTimerTask mVideoTimerTask;
    //    private ChatTimerTask mChatTimerTask;
    private long streamChannelID;
    private String streamVideoUrl;
    private static boolean LEVAE_MODE = false;
    private static boolean hasPullMemberList = false;
    //    private MemberListAdapter memberAdapter;
//    private MemberListDialog mMemberListDialog;
    private ArrayAdapter spinnerAdapter;
    private static final String[] SDKtype = {"普通开发SDK业务", "普通物联网摄像头SDK业务", "滨海摄像头SDK业务"};
    private static final int MAX_REQUEST_VIEW_COUNT = 3;//当前最大支持请求画面个数
    //    private String selectIdentier = "";
//    private FrameLayout mInviteMastk1, mInviteMastk2, mInviteMastk3;
//    private ImageView mVideoHead1, mVideoHead2, mVideoHead3;
    private CircularImageButton hostHead;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private MemberInfo hostMember;
    private Boolean OpenVoice = false;
    private Boolean OpenVideo = false;
    private int mMaskViewCount = 0;
    private HashMap<String, Integer> viewIndex = new HashMap<String, Integer>();
    //正在发起请求的id
    private ArrayList<String> requestId = new ArrayList<String>();

    LinearLayout mBottomInputBar;
    RelativeLayout mBottomToolBar;
    View mBlackPlace;
    TextView mUserCount;
    ImageView mToChat;
    HorizontalListView mMemberListLayout;
    LinearLayout mMemberScrollLayout;
    PeriscopeLayout mFavorLayout;
    ImageView mShareBtn;
    ImageView mGiftBtn;
    ViewPager mEmotionVp;
    LinearLayout mPayLayout;
    LinearLayout mEmotionLayout;
    TextView mSendGift;
    DanMuView mDanmu;
    RelativeLayout mDanmuOnLayout;
    RelativeLayout mDanmuOffLayout;
    RelativeLayout mGiftBottom;
    RelativeLayout mGiftTop;
    TextView mPopulatorText;
    LinearLayout mPopulatorLayout;
    TextView mDiamondCount;
    FrameLayout mDanmuSwitchBtn;
    private LinearLayout gifView;
    private ImageView gifImg;
    private volatile boolean gifViewIsBusy;
    private ArrayList<GifTask> gifViewTaskList = new ArrayList();
//    TextView mLiveLabel;


    //用于动态展示人气值
    private int mPopulatorCount;


    @InjectView(R.id.viewPager)
    ViewPager mViewPager;
    @InjectView(R.id.close)
    View mCloseBtn;

    private List<View> lists = new ArrayList<View>();
    private AvChatAdapter mAvChatAdapter;

    private boolean mIsDanmuOn = false;
    private GiftAdapter mGiftAdapter;

    private int mUserCountInteger = 0;
    private static int maxUserListSize = 60;
    private static int minUserListSize = 50;

//    @InjectView(R.id.viewpager)
//    ViewPager mViewPager;

    //消息类型
    public Constants.MESSAGETYPE msgType = Constants.MESSAGETYPE.MESSAGE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "WL_DEBUG onCreate start");
        super.onCreate(savedInstanceState);
        ctx = this;
        setContentView(R.layout.av_activity);
        ButterKnife.inject(this);
        registerBroadcastReceiver();

        showDialog(DIALOG_INIT);
        Util.switchWaitingDialog(ctx, mDialogInit, DIALOG_INIT, true);
        mQavsdkApplication = (XLApplication) getApplication();
        mQavsdkControl = mQavsdkApplication.getQavsdkControl();
        int netType = Util.getNetWorkType(ctx);//网络状态
        Log.e(TAG, "WL_DEBUG connectionReceiver onCreate = " + netType);
        if (netType != AVConstants.NETTYPE_NONE) {
            mQavsdkControl.setNetType(Util.getNetWorkType(ctx));
        }

        if (mQavsdkControl.getAVContext() != null) {
            mQavsdkControl.onCreate((XLApplication) getApplication(), findViewById(android.R.id.content));
        } else {
            finish();
        }
        mQavsdkControl.setRequestCount(0);
//        mSelfUserInfo = mQavsdkApplication.getMyselfUserInfo();
        mMemberList = mQavsdkControl.getMemberList();
        mNormalMemberList = copyToNormalMember();
        roomNum = getIntent().getExtras().getInt(Util.EXTRA_ROOM_NUM);//房间号
        groupForPush = roomNum;
//        if (mSelfUserInfo.getEnv() == Util.ENV_TEST) {
//			groupForPush = Integer.parseInt(mSelfUserInfo.getUserPhone().substring(0, 5));
//            groupForPush = 14010;
//        }
//        mRecvIdentifier = "" + roomNum;
        mHostIdentifier = getIntent().getExtras().getString(Util.EXTRA_SELF_IDENTIFIER);//用户id
        Log.d(TAG, "onCreate mHostIdentifier" + mHostIdentifier);

        groupId = getIntent().getExtras().getString(Util.EXTRA_GROUP_ID);//房间号
        if (!Constants.isCreater) {
            praiseNum = getIntent().getExtras().getInt(Util.EXTRA_PRAISE_NUM);
        }
        mIsSuccess = false;
        mRequestIdentifierList = new String[MAX_REQUEST_VIEW_COUNT];
        mRequestViewList = new AVView[MAX_REQUEST_VIEW_COUNT];
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs().build();
        ImageLoader.getInstance().init(config);
        initView();
        initGiftView();
    }

    private void initView() {
        View content = getLayoutInflater().inflate(R.layout.qav_bottom_bar, null);
        lists.add(getLayoutInflater().inflate(R.layout.view_emptyview, null));
        lists.add(content);
        mAvChatAdapter = new AvChatAdapter(lists);
        mViewPager.setAdapter(mAvChatAdapter);
        mViewPager.setCurrentItem(1);

        gifView = (LinearLayout) findViewById(R.id.gif_view);
        gifImg = (ImageView) gifView.findViewById(R.id.gif_img);
        mBottomInputBar = (LinearLayout) content.findViewById(R.id.qav_bottom_input_bar);
        mBottomToolBar = (RelativeLayout) content.findViewById(R.id.qav_bottom_tool_bar);
        mBlackPlace = (View) content.findViewById(R.id.black_place);
        mUserCount = (TextView) content.findViewById(R.id.user_count);
        mToChat = (ImageView) content.findViewById(R.id.qav_topbar_chat);
        mMemberListLayout = (HorizontalListView) content.findViewById(R.id.member_list_layout);
        mMemberListLayout.setVisibility(View.GONE);
        mMemberScrollLayout = (LinearLayout) content.findViewById(R.id.member_ll_layout);
        (content.findViewById(R.id.member_hsv_layout)).setVisibility(View.VISIBLE);
        mFavorLayout = (PeriscopeLayout) content.findViewById(R.id.zan_layout);
        mShareBtn = (ImageView) content.findViewById(R.id.share_btn);
        mGiftBtn = (ImageView) content.findViewById(R.id.gift_btn);
        mEmotionVp = (ViewPager) content.findViewById(R.id.emotion_viewpager);
        mPayLayout = (LinearLayout) content.findViewById(R.id.pay_bottom_layout);
        mEmotionLayout = (LinearLayout) content.findViewById(R.id.emotion_layout);
        mSendGift = (TextView) content.findViewById(R.id.send_gift);
        mDanmu = (DanMuView) content.findViewById(R.id.tanmu);
        mDanmuOnLayout = (RelativeLayout) content.findViewById(R.id.danmu_on_layout);
        mDanmuOffLayout = (RelativeLayout) content.findViewById(R.id.danmu_off_layout);
        mGiftBottom = (RelativeLayout) content.findViewById(R.id.gift_bottom);
        mGiftTop = (RelativeLayout) content.findViewById(R.id.gift_top);
        mPopulatorText = (TextView) content.findViewById(R.id.populator_num);
        mPopulatorLayout = (LinearLayout) content.findViewById(R.id.populator_layout);
        mDiamondCount = (TextView) content.findViewById(R.id.diamond_count);
        mDanmuSwitchBtn = (FrameLayout) content.findViewById(R.id.danmu_switch);
//        mLiveLabel = (TextView) content.findViewById(R.id.live_label);

        mGiftViewTopHolder = new GiftViewHolder();
        mGiftViewBottomHolder = new GiftViewHolder();
        mGiftViewTopHolder.initViews((ViewGroup) mGiftTop);
        mGiftViewBottomHolder.initViews((ViewGroup) mGiftBottom);


        mCloseBtn.setOnClickListener(this);
        mBottomInputBar.setOnClickListener(this);
        mBlackPlace.setOnClickListener(this);
        mToChat.setOnClickListener(this);
        mFavorLayout.setOnClickListener(this);
        mShareBtn.setOnClickListener(this);
        mGiftBtn.setOnClickListener(this);
        mPayLayout.setOnClickListener(this);
        mSendGift.setOnClickListener(this);
        mDanmuOnLayout.setOnClickListener(this);
        mDanmuOffLayout.setOnClickListener(this);
        mPopulatorLayout.setOnClickListener(this);


        ImageView mButtonSwitchCamera;
        hostHead = (CircularImageButton) content.findViewById(R.id.host_head);
        mButtonSwitchCamera = (ImageView) content.findViewById(R.id.qav_topbar_switchcamera);
        mListViewMsgItems = (ListView) content.findViewById(R.id.im_msg_items);
        View view = LayoutInflater.from(AvActivity.this).inflate(R.layout.view_msg_list_header, null, false);
        TextView contentTv = (TextView) view.findViewById(R.id.content);
        String name = "系统消息:";
        String body = "星聊是体育明星与粉丝进行互动的直播平台，鼓励大家踊跃发言，禁止发表涉及政治、色情、广告等相关的言论.";
        SpannableStringBuilder builder = new SpannableStringBuilder(name + body);
        ForegroundColorSpan yellowSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_text_5));
        ForegroundColorSpan whiteSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_FA2E61));
        builder.setSpan(yellowSpan, 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(whiteSpan, name.length(), name.length() + body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        contentTv.setText(builder);
        mListViewMsgItems.addHeaderView(view);
        if (Integer.parseInt(Build.VERSION.SDK) >= 9) {
            mListViewMsgItems.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
//        mListViewMsgItems.setOnClickListener(this);
        mEditTextInputMsg = (EditText) content.findViewById(R.id.qav_bottombar_msg_input);
        mEditTextInputMsg.setOnClickListener(this);
        mEditTextInputMsg.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    msgType = Constants.MESSAGETYPE.MESSAGE;//普通消息发送
                    onSendMsg();
                    return true;
                }
                return false;
            }
        });

        content.findViewById(R.id.qav_topbar_hangup).setOnClickListener(this);
//        findViewById(R.id.qav_topbar_push).setOnClickListener(this);
//        findViewById(R.id.qav_topbar_record).setOnClickListener(this);
        mButtonSendMsg = (Button) content.findViewById(R.id.qav_bottombar_send_msg);
        mButtonSendMsg.setOnClickListener(this);
        mClockTextView = (TextView) content.findViewById(R.id.qav_timer);
//        mPraiseNum = (TextView) findViewById(R.id.text_view_live_praise);
//        mMemberListButton = (TextView) findViewById(R.id.btn_member_list);
//        mMemberListButton.setOnClickListener(this);
        mButtonPraise = (ImageView) content.findViewById(R.id.image_btn_praise);
        mButtonPraise.setOnClickListener(this);
        mGiftBtn.setOnClickListener(this);

        if (Constants.isCreater) {
            mButtonSwitchCamera.setVisibility(View.VISIBLE);
            mButtonPraise.setVisibility(View.GONE);
            mGiftBtn.setVisibility(View.GONE);
            mDanmuSwitchBtn.setVisibility(View.GONE);
        } else {
            mButtonSwitchCamera.setVisibility(View.GONE);
            mButtonPraise.setVisibility(View.VISIBLE);
            mGiftBtn.setVisibility(View.VISIBLE);
            mDanmuSwitchBtn.setVisibility(View.VISIBLE);
        }
        AVAudioCtrl avAudioCtrl = mQavsdkControl.getAVContext().getAudioCtrl();
        if (Constants.isCreater) {
            mButtonSwitchCamera.setOnClickListener(this);

//            avAudioCtrl.enableMic(false);
            avAudioCtrl.enableMic(true);
          } else {
            mButtonSwitchCamera.setOnClickListener(this);
            mQavsdkControl.getAVContext().getAudioCtrl().enableMic(false);
            avAudioCtrl.enableMic(false);
//            mPraiseNum.setText("" + praiseNum);
//            mButtonMute.setVisibility(View.GONE);
//            mButtonSwitchCamera.setVisibility(View.GONE);
        }

        //不熄屏
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "TAG");

        //默认不显示键盘
        mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        findViewById(R.id.av_screen_layout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hideMsgIputKeyboard();
                mEditTextInputMsg.setVisibility(View.VISIBLE);
                return false;
            }
        });

        mVideoTimer = new Timer(true);
        mHeartClickTimer = new Timer(true);

        if (Constants.isCreater) {//是否是创建者
            startRecord();//录制直播
            Push();//开启推送功能通知自己的人观看直播
        }
//        mMemberListLayout.setAdapter(mMemberListAdapter);
        mDiamondCount.setText(PreferencesStorageUtil.getDiamondCount(AvActivity.this) + "");
        enterRoom();//进入房间
        getRoomInfo();

//        timer.schedule(task, TIMER_INTERVAL, TIMER_INTERVAL);
    }


    EditText pushfileNameInput, pushClassInput, pushInfoInput, pushCodeInput;

    private class VideoTimerTask extends TimerTask {
        public void run() {
            ++second;
            mHandler.sendEmptyMessage(UPDAT_WALL_TIME_TIMER_TASK);
        }
    }

//    private class ChatTimerTask extends TimerTask {
//        @Override
//        public void run() {
//            mHandler.sendEmptyMessage(REMOVE_CHAT_ITEM_TIMER_TASK);
//        }
//    }

    private TimerTask mHeartClickTask = new TimerTask() {
        @Override
        public void run() {
            heartClick();
        }
    };

    //收消息
    private TIMMessageListener msgListener = new TIMMessageListener() {
        @Override
        public boolean onNewMessages(List<TIMMessage> list) {

            Log.d(TAG, "onNewMessagesGet  " + list.size());
//            if (isTopActivity()) {
            //解析TIM推送消息
            if (groupId != null) {
                refreshChat2(list);
            }
//            }
            return false;
        }
    };

    //礼物展示相关信息
    private List<TIMGiftModel> mGiftList = new ArrayList<>();
    private boolean isGiftQueue1busy = false;
    private boolean isGiftQueue2busy = false;

    GiftViewHolder mGiftViewTopHolder;
    GiftViewHolder mGiftViewBottomHolder;
    private static final int TIME_GIFT_DISAPEAR = 3000;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_PRAISE://自定义消息
                    if (praiseNum == 0)
                        praiseNum++;
//                    mPraiseNum.setText("" + praiseNum);
                    break;

                case SHOW_GIFT:

                    synchronized (mGiftList) {
                        if (mGiftList.size() > 0) {
                            if (!isGiftQueue1busy) {
                                //如果第一个队列不忙
                                TIMGiftModel timGiftModel = mGiftList.remove(0);
                                mGiftViewTopHolder.bindView(timGiftModel);
                                if(timGiftModel.getBig_image()==null || timGiftModel.getBig_image().equals("")) {
                                    mGiftViewTopHolder.show();//礼物的动画
                                }
                                isGiftQueue1busy = true;
                                mHandler.sendEmptyMessageDelayed(GIFTLIST_1_DISMISS, TIME_GIFT_DISAPEAR);
                                msgType = Constants.MESSAGETYPE.GIFTMESSAGE;
                                showGifMessage(timGiftModel.getUserId(), timGiftModel.getName(), timGiftModel.getDesc());
                                if (timGiftModel.getBig_image() != null && !timGiftModel.getBig_image().equals("")) {
                                    String giftDes = timGiftModel.getName() + "送出了" + timGiftModel.getDesc();
                                    showGifView(giftDes, timGiftModel.getBig_image(), timGiftModel.getDirection(), true);
                                }
//                                else {
//                                    showGifView("丑丑送出的大飞机", "http://7xry7i.com1.z0.glb.clouddn.com/biggift%2F%E9%A3%9E%E6%9C%BA.png", "plane", true);
//                                }
                            } else if (!isGiftQueue2busy) {
                                //如果第二个队列不忙
                                TIMGiftModel timGiftModel = mGiftList.remove(0);
                                mGiftViewBottomHolder.bindView(timGiftModel);
                                if(timGiftModel.getBig_image()==null || timGiftModel.getBig_image().equals("")) {
                                    mGiftViewTopHolder.show();//礼物的动画
                                }
                                isGiftQueue2busy = true;
                                mHandler.sendEmptyMessageDelayed(GIFTLIST_2_DISMISS, TIME_GIFT_DISAPEAR);
                                msgType = Constants.MESSAGETYPE.GIFTMESSAGE;
                                showGifMessage(timGiftModel.getUserId(), timGiftModel.getName(), timGiftModel.getDesc());
                                if (timGiftModel.getBig_image() != null && !timGiftModel.getBig_image().equals("")) {
                                    String giftDes = timGiftModel.getName() + "送出了" + timGiftModel.getDesc();
                                    showGifView(giftDes, timGiftModel.getBig_image(), timGiftModel.getDirection(), true);
                                }
//                                else {
//                                    showGifView("丑丑送出的大汽车", "http://7xry7i.com1.z0.glb.clouddn.com/biggift%2F%E6%B1%BD%E8%BD%A6.png", "car", true);
//                                }
                            }
                            //如果都忙，就不管了，队列展示结束后会再次调用 SHOW_GIFT
                        }
                    }
                    break;

                case GIFTLIST_1_DISMISS:
                    mGiftViewTopHolder.dismiss();
                    isGiftQueue1busy = false;
                    mHandler.sendEmptyMessage(SHOW_GIFT);
                    break;
                case GIFTLIST_2_DISMISS:
                    mGiftViewBottomHolder.dismiss();
                    isGiftQueue2busy = false;
                    mHandler.sendEmptyMessage(SHOW_GIFT);
                    break;

                case IM_HOST_LEAVE:
//                    onMemberExit();
                    onCloseVideo();
                    break;

                case ERROR_MESSAGE_TOO_LONG:
                    Toast.makeText(getBaseContext(), "消息太长，发送失败", Toast.LENGTH_SHORT).show();
                    break;
                case ERROR_ACCOUNT_NOT_EXIT:
                    Toast.makeText(getBaseContext(), "对方账号不存在或未登陆过！", Toast.LENGTH_SHORT).show();
                    break;

                case UPDAT_WALL_TIME_TIMER_TASK:
                    updateWallTime();
                    break;
//                case REMOVE_CHAT_ITEM_TIMER_TASK:
//                    removeChatItem();
//                    break;
                case UPDAT_MEMBER:
                    updateMemberView();
//                    mChatMsgListAdapter.refresh(hostMember);
                    break;
                case MEMBER_EXIT_COMPLETE://退出聊天室
                    sendCloseMsg();
                    break;
                case CLOSE_VIDEO:
                    onCloseVideo();
                    break;
//                case START_RECORD:
//                    startRecord();
//                    break;
                case GET_ROOM_INFO://进房间
                    getMemberInfo();
                    break;
                case REFRESH_CHAT:
                    showTextMessage((TIMMessage) msg.obj);
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    //TODO cc 播放全屏动画
    private void showGifView(String des, String url, String type, final boolean needWait) {
        synchronized (this) {
            if (gifViewIsBusy && needWait) {
                gifViewTaskList.add(new GifTask(des, url, type));
            } else {
                gifViewIsBusy = true;
                gifView.setVisibility(View.VISIBLE);
                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                float width = metric.widthPixels / 2;
                Picasso.with(AvActivity.this).load(url).placeholder(R.drawable.ic_launcher).into(gifImg);
                ((TextView) gifView.findViewById(R.id.gif_txt)).setText(des);
                if (type.equals("lt_to_rb")) {
                    ObjectAnimator carInXAnimation = ObjectAnimator.ofFloat(gifView, "translationX", -500 - 100, 0f);
                    carInXAnimation.setDuration(700);
                    ObjectAnimator carInYAnimation = ObjectAnimator.ofFloat(gifView, "translationY", -200, 0f);
                    carInYAnimation.setDuration(700);
                    ObjectAnimator carStandAnimation = ObjectAnimator.ofFloat(gifView, "translationY", 0f, 0f);
                    carStandAnimation.setDuration(1100);
                    ObjectAnimator carOutXAnimation = ObjectAnimator.ofFloat(gifView, "translationX", 0f, 500 + 100);
                    carOutXAnimation.setDuration(700);
                    ObjectAnimator carOutYAnimation = ObjectAnimator.ofFloat(gifView, "translationY", 0f, 200);
                    carOutYAnimation.setDuration(700);
                    AnimatorSet animatorSet1 = new AnimatorSet();
                    animatorSet1.play(carInXAnimation).with(carInYAnimation).before(carStandAnimation);
                    animatorSet1.play(carOutXAnimation).with(carOutYAnimation).after(carStandAnimation);
                    carOutYAnimation.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            gifView.setVisibility(View.INVISIBLE);
                            Log.e("cc", "Car anim finished");
                            synchronized (gifViewTaskList) {
                                    if (gifViewTaskList.size() > 0) {
                                        showGifView(gifViewTaskList.get(0).des, gifViewTaskList.get(0).url, gifViewTaskList.get(0).type, false);
                                        gifViewTaskList.remove(0);
                                    }else if (gifViewTaskList.size() == 0) {
                                        gifViewIsBusy = false;
                                    }
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animatorSet1.start();
                } else if (type.equals("rt_to_lb")) {
                    ObjectAnimator planeInXAnimation = ObjectAnimator.ofFloat(gifView, "translationX", -width - 100, width + 100);
                    planeInXAnimation.setDuration(2500);
                    ObjectAnimator planeInYAnimation = ObjectAnimator.ofFloat(gifView, "translationY", 200, -200f);
                    planeInYAnimation.setDuration(2500);
                    AnimatorSet animatorSet2 = new AnimatorSet();
                    animatorSet2.play(planeInXAnimation).with(planeInYAnimation);
                    planeInYAnimation.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            gifView.setVisibility(View.INVISIBLE);
                            synchronized (gifViewTaskList) {
                                if (gifViewTaskList.size() > 0) {
                                    showGifView(gifViewTaskList.get(0).des, gifViewTaskList.get(0).url, gifViewTaskList.get(0).type, false);
                                    gifViewTaskList.remove(0);
                                }else if (gifViewTaskList.size() == 0) {
                                    gifViewIsBusy = false;
                                }
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animatorSet2.start();
                }
            }
        }
    }

    private static final int FLAG_PAY = 1001;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FLAG_PAY:
                mDiamondCount.setText(PreferencesStorageUtil.getDiamondCount(AvActivity.this) + "");
                break;

        }

    }

    private BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mobileInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Log.e(TAG, "WL_DEBUG netinfo mobile = " + mobileInfo.isConnected() + ", wifi = " + wifiInfo.isConnected());

            int netType = Util.getNetWorkType(ctx);
            Log.e(TAG, "WL_DEBUG connectionReceiver getNetWorkType = " + netType);
            mQavsdkControl.setNetType(netType);

            if (!mobileInfo.isConnected() && !wifiInfo.isConnected()) {
                Log.e(TAG, "WL_DEBUG connectionReceiver no network = ");
                // unconnect network
                // 暂时不关闭
//				if (ctx instanceof Activity) {
//					Toast.makeText(getApplicationContext(), ctx.getString(R.string.notify_no_network), Toast.LENGTH_SHORT).show();
//					((Activity)ctx).finish();
//				}
            } else {
                // connect network
            }
        }
    };

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive action = " + action);
            if (action.equals(Util.ACTION_SURFACE_CREATED)) {
                locateCameraPreview();
                wakeLock.acquire();
//                mQavsdkControl.toggleEnableCamera();
                if (Constants.isCreater == true) {
                    initTIMGroup();
                    mEditTextInputMsg.setClickable(true);
                    mIsSuccess = true;
                    mVideoTimer = new Timer(true);
                    mVideoTimerTask = new VideoTimerTask();
                    mVideoTimer.schedule(mVideoTimerTask, 1000, 1000);
                    mHeartClickTimer.schedule(mHeartClickTask, 1000, 30000);
                    mQavsdkControl.toggleEnableCamera();
                    boolean isEnable = mQavsdkControl.getIsEnableCamera();
                    refreshCameraUI();
                    if (mOnOffCameraErrorCode != AVError.AV_OK) {
                        showDialog(isEnable ? DIALOG_OFF_CAMERA_FAILED : DIALOG_ON_CAMERA_FAILED);
                        mQavsdkControl.setIsInOnOffCamera(false);
                        refreshCameraUI();
                    }
//                    Log.d(TAG, "getMemberInfo isHandleMemberRoomSuccess " + mQavsdkApplication.isHandleMemberRoomSuccess());

//                    if (mQavsdkApplication.isHandleMemberRoomSuccess()) {
//                        Log.d(TAG, "getMemberInfo isHandleMemberRoomSuccess " + mQavsdkApplication.isHandleMemberRoomSuccess() + " yes  do it normally ");
                    mHandler.sendEmptyMessageDelayed(GET_ROOM_INFO, 0);
//                    } else {
//                        Log.w(TAG, "getMemberInfo isHandleMemberRoomSuccess " + mQavsdkApplication.isHandleMemberRoomSuccess() + " no wait for call");
//                    }
                    mQavsdkControl.setRequestCount(0);
                    //上报主播心跳
//                    mHeartClickTimer.schedule(mHeartClickTask, 1000, 30000);
                } else {

                    hostRequestView(mHostIdentifier);//242
                }
            } else if (action.equals(Util.ACTION_VIDEO_CLOSE)) {
                String identifier = intent.getStringExtra(Util.EXTRA_IDENTIFIER);
                if (!TextUtils.isEmpty(mRecvIdentifier)) {
                    mQavsdkControl.setRemoteHasVideo(false, mRecvIdentifier, 0);
                }

                mRecvIdentifier = identifier;
            } else if (action.equals(Util.ACTION_VIDEO_SHOW)) {
                //成员模式加入视频聊天室
                String identifier = intent.getStringExtra(Util.EXTRA_IDENTIFIER);
                Log.d(TAG, "onReceive ACTION_VIDEO_SHOW  id " + identifier);
                mRecvIdentifier = identifier;
                mQavsdkControl.setRemoteHasVideo(true, mRecvIdentifier, 0);
                //IMSDk 加入聊天室
                joinGroup();
                initTIMGroup();
                mIsSuccess = true;
                mEditTextInputMsg.setClickable(true);
                //获取群组成员信息
                getMemberInfo();
                //发消息通知大家 自己上线了
                onMemberEnter();
                Util.switchWaitingDialog(ctx, mDialogInit, DIALOG_INIT, false);
            } else if (action.equals(Util.ACTION_ENABLE_CAMERA_COMPLETE)) {
                Log.d(TAG, "onClick ACTION_ENABLE_CAMERA_COMPLETE   " + " status " + mQavsdkControl.getIsEnableCamera());
                mQavsdkControl.getAVContext().getVideoCtrl().enableBeauty(true);
                mQavsdkControl.getAVContext().getVideoCtrl().inputBeautyParam(5.0f);
                //自己是主播才本地渲染摄像头界面
                if (Constants.isCreater == true) {

                    refreshCameraUI();

                    mOnOffCameraErrorCode = intent.getIntExtra(Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);
                    boolean isEnable = intent.getBooleanExtra(Util.EXTRA_IS_ENABLE, false);

                    if (mOnOffCameraErrorCode == AVError.AV_OK) {
                        if (!mIsPaused) {
                            Log.d(TAG, "ACTION_ENABLE_CAMERA_COMPLETE mHostIdentifier " + mHostIdentifier);
//                            if (!mHostIdentifier.startsWith("86-")) {
//                                mHostIdentifier = "86-" + mHostIdentifier;
//                            }
                            mQavsdkControl.setSelfId(mHostIdentifier);
                            mQavsdkControl.setLocalHasVideo(isEnable, mHostIdentifier);
//                            startDefaultRecord();
                        }
                    } else {
                        showDialog(isEnable ? DIALOG_ON_CAMERA_FAILED : DIALOG_OFF_CAMERA_FAILED);
                    }

                    if (currentCameraIsFront == false) {
                        Log.d(TAG, " onSwitchCamera!!ACTION_ENABLE_CAMERA_COMPLETE and lastTime is backCamera :  " + mQavsdkControl.getIsInOnOffCamera());
                        onSwitchCamera();
                    }
                }
            } else if (action.equals(Util.ACTION_SWITCH_CAMERA_COMPLETE)) {
                Log.d(TAG, " onSwitchCamera!! ACTION_SWITCH_CAMERA_COMPLETE  " + mQavsdkControl.getIsInOnOffCamera());
                refreshCameraUI();

                mSwitchCameraErrorCode = intent.getIntExtra(Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);
                boolean isFront = intent.getBooleanExtra(Util.EXTRA_IS_FRONT, false);
                if (mSwitchCameraErrorCode != AVError.AV_OK) {
                    showDialog(isFront ? DIALOG_SWITCH_FRONT_CAMERA_FAILED : DIALOG_SWITCH_BACK_CAMERA_FAILED);
                } else {
                    currentCameraIsFront = mQavsdkControl.getIsFrontCamera();
                    Log.d(TAG, "onSwitchCamera  " + currentCameraIsFront);
                }
            } else if (action.equals(Util.ACTION_INSERT_ROOM_TO_SERVER_COMPLETE)) {
                Log.w(TAG, "getMemberInfo isHandleMemberRoomSuccess " + mQavsdkApplication.isHandleMemberRoomSuccess() + " now is time ");
                mHandler.sendEmptyMessageDelayed(GET_ROOM_INFO, 0);
            }


        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        if (Constants.isCreater == true)
            if (mQavsdkControl.getIsEnableCamera() == false) {
                mQavsdkControl.toggleEnableCamera();
                OpenVideo = true;

            }
        AVAudioCtrl avAudioCtrl = mQavsdkControl.getAVContext().getAudioCtrl();
        avAudioCtrl.enableMic(true);
        OpenVoice = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsPaused = false;
        LEVAE_MODE = false;
        mQavsdkControl.onResume();
        Log.i(TAG, "onResume switchCamera!! ");
        refreshCameraUI();

        if (mOnOffCameraErrorCode != AVError.AV_OK) {
            showDialog(DIALOG_ON_CAMERA_FAILED);
        }
//        startOrientationListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsPaused = true;
        mQavsdkControl.onPause();
        Log.i(TAG, "onPause switchCamera!! ");
        refreshCameraUI();
        if (mOnOffCameraErrorCode != AVError.AV_OK) {
            showDialog(DIALOG_OFF_CAMERA_FAILED);
        }
//        stopOrientationListener();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //关闭摄像头
        if (mQavsdkControl.getIsEnableCamera() == true) {
            mQavsdkControl.toggleEnableCamera();
            OpenVideo = false;
        }
        //关闭Mic
//        mQavsdkControl.setRequestCount(0);
        AVAudioCtrl avAudioCtrl = mQavsdkControl.getAVContext().getAudioCtrl();
        avAudioCtrl.enableMic(false);
        OpenVoice = false;
        mQavsdkApplication.setHandleMemberRoomSuccess(false);
        hasPullMemberList = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMaskViewCount = 0;
        mQavsdkControl.onDestroy();
        // 注销广播
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }

        if (mChatTimer != null) {
            mChatTimer.cancel();
        }
        if (mVideoTimer != null) {
            mVideoTimer.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
        if (mHeartClickTimer != null) {
            mHeartClickTimer.cancel();
        }

        Log.d(TAG, "WL_DEBUG onDestroy");
        Util.switchWaitingDialog(ctx, mDialogAtDestroy, DIALOG_DESTROY, false);
    }

    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Util.ACTION_SURFACE_CREATED);
        intentFilter.addAction(Util.ACTION_VIDEO_SHOW);
//        intentFilter.addAction(Util.ACTION_MEMBER_VIDEO_SHOW);
        intentFilter.addAction(Util.ACTION_VIDEO_CLOSE);
        intentFilter.addAction(Util.ACTION_ENABLE_CAMERA_COMPLETE);
        intentFilter.addAction(Util.ACTION_SWITCH_CAMERA_COMPLETE);
        intentFilter.addAction(Util.ACTION_INSERT_ROOM_TO_SERVER_COMPLETE);
        registerReceiver(mBroadcastReceiver, intentFilter);

        IntentFilter netIntentFilter = new IntentFilter();
        netIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, netIntentFilter);
    }

    //进入房间通知服务端
    private void enterRoom() {
        XLApplication.getInstance().getRestClient().enterRoom(roomNum + "", UserUtils.getUserInstance().getNickname(), new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                mHandler.sendEmptyMessageDelayed(GET_ROOM_INFO, 0);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_ROOM_NUM, Constants.getChooseRoomInfo().getId());
//                    object.put(Util.EXTRA_USER_PHONE, PreferencesStorageUtil.getUserId(Main2Activity.this));
//                    System.out.println(object.toString());
//                    List<NameValuePair> list = new ArrayList<NameValuePair>();
//                    list.add(new BasicNameValuePair("viewerdata", object.toString()));
//                    String ret = HttpUtil.PostUrl(HttpUtil.enterRoomUrl, list);
//                    Log.d(TAG, "enter room" + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    private RoomBean mRoomBean;

    private void getRoomInfo() {//获取房间信息
        XLApplication.getInstance().getRestClient().getFeedInfo(roomNum + "", new Callback<RoomBean>() {
            @Override
            public void success(RoomBean roomBean, Response response) {
                if (roomBean != null) {
                    mRoomBean = roomBean;
                    mPopulatorText.setText(roomBean.getUser().getTotal_popularity() + "");
                    mPopulatorCount = roomBean.getUser().getTotal_popularity();
                    hostMember = new MemberInfo(roomBean.getUser().getId(),
                            roomBean.getUser().getNickname(),
                            roomBean.getUser().getAvatar());
                    if (mChatMsgListAdapter != null) {
                        mChatMsgListAdapter.refreshHost(hostMember);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void initTIMGroup() {
        Log.d(TAG, "initTIMGroup groupId" + groupId);
        if (groupId != null) {
            //获取群聊会话
            //TIMConversationType.C2C, //会话类型：单聊 peer); //会话对方用户帐号//对方id
            mConversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, groupId);
            Log.d(TAG, "initTIMGroup mConversation" + mConversation);
        } else {

        }
        mSystemConversation = TIMManager.getInstance().getConversation(TIMConversationType.System, "");
//        testConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, "18602833226");
        mArrayListChatEntity = new ArrayList<ChatEntity>();
        mChatMsgListAdapter = ChatMsgListAdapter.createInstanceFromMemList(this, mArrayListChatEntity, mMemberList,
                hostMember, new ChatMsgListAdapter.MemberListCallBack() {
                    @Override
                    public void onCommentClick(CommentBean commentBean) {
                        CommentDialogFragment mCommentDialogFragment = CommentDialogFragment.newInstance(commentBean);
                        mCommentDialogFragment.show(getSupportFragmentManager().beginTransaction(), "show_member");
                    }

                    @Override
                    public void onUserInfoClick(String userId) {
                        getUserInfo(userId);
                    }
                });
        mListViewMsgItems.setAdapter(mChatMsgListAdapter);
        if (mListViewMsgItems.getCount() > 1)
            mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
        mListViewMsgItems.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideMsgIputKeyboard();
                mEditTextInputMsg.setVisibility(View.VISIBLE);
                return false;
            }
        });

        mListViewMsgItems.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        if (view.getFirstVisiblePosition() == 0 && !mIsLoading && bMore) {
                            bNeverLoadMore = false;
                            mIsLoading = true;
                            mLoadMsgNum += MAX_PAGE_NUM;
//							getMessage();
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
//        getMessage();

        TIMManager.getInstance().addMessageListener(msgListener);//接受消息的监听

        mChatTimer = new Timer(true);
        time = System.currentTimeMillis() / 1000;
//        mChatTimerTask = new ChatTimerTask();
//        mChatTimer.schedule(mChatTimerTask, 8000, 2000);
    }

    public void getUserInfo(final String userId) {
        XLApplication.getInstance().getRestClient().getUserInfo(userId, new Callback<UserBean>() {
            @Override
            public void success(UserBean userBean, Response response) {
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setUserName(userBean.getNickname());
                memberInfo.setHeadImagePath(userBean.getAvatar());
                MemberDialogFragment memberDialogFragment = MemberDialogFragment.newInstance(memberInfo);
                memberDialogFragment.show(getSupportFragmentManager().beginTransaction(), "show_member");
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    //退出聊天室
    private void destroyTIM() {
        TIMManager.getInstance().removeMessageListener(msgListener);
        Log.d(TAG, "WL_DEBUG onDestroy");
        if (groupId != null && mIsSuccess) {
            if (Constants.isCreater) {
                TIMGroupManager.getInstance().deleteGroup(groupId, new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG, "quit group error " + i + " " + s);
                    }

                    @Override
                    public void onSuccess() {
                        Log.e(TAG, "delete group success");
                        Log.d(TAG, "WL_DEBUG onDestroy");
                    }
                });
            } else {
                TIMGroupManager.getInstance().quitGroup(groupId, new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG, "quit group error " + i + " " + s);
                    }

                    @Override
                    public void onSuccess() {
                        Log.i(TAG, "delete group success");
                        Log.i(TAG, "WL_DEBUG onDestroy");
                    }
                });
            }
            TIMManager.getInstance().deleteConversation(TIMConversationType.Group, groupId);
        }
    }

    private void joinGroup() {
        TIMGroupManager.getInstance().applyJoinGroup(groupId, "申请加入" + groupId, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
//                TIMManager.getInstance().logout();
                Toast.makeText(ctx, "加群失败,失败原因：" + i + ":" + s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess() {
                Log.i(TAG, "applyJpoinGroup success");
            }
        });
    }


    private void refreshChat2(List<TIMMessage> msg) {
        Log.d(TAG, "refreshChat 0000 " + msg);
        List<TIMMessage> tlist = msg;


        if (tlist.size() > 0) {
            mConversation.setReadMessage(tlist.get(0));
            Log.d(TAG, "refreshChat readMessage " + tlist.get(0).timestamp());
        }
        if (!bNeverLoadMore && (tlist.size() < mLoadMsgNum))
            bMore = false;

        for (int i = tlist.size() - 1; i >= 0; i--) {
            Log.d(TAG, "refreshChat 2222curMsg");
            TIMMessage currMsg = tlist.get(i);


            for (int j = 0; j < currMsg.getElementCount(); j++) {


                if (currMsg.getElement(j) == null)
                    continue;
                TIMElem elem = currMsg.getElement(j);
                TIMElemType type = elem.getType();
                Log.i(TAG, "refreshChat2 type " + type);


                //系统消息
                if (type == TIMElemType.GroupSystem) {
                    Log.d(TAG, "getSysMessage !!!! cuonNewMessagesrMsg    " + ((TIMGroupSystemElem) elem).getSubtype());
                    if (TIMGroupSystemElemType.TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE == ((TIMGroupSystemElem) elem).getSubtype()) {
                        mHandler.sendEmptyMessage(IM_HOST_LEAVE);
                        LEVAE_MODE = true;
                    }

                }

                //定制消息
                if (type == TIMElemType.Custom) {
                    handleCustomMsg(elem);
                    continue;
                }

                //其他群消息过滤
                if (!groupId.equals(currMsg.getConversation().getPeer())) {
                    continue;
                }

                ChatEntity entity = new ChatEntity();
                entity.setElem(elem);
                entity.setIsSelf(currMsg.isSelf());
                Log.d(TAG, "refreshChat2 " + currMsg.isSelf());
                entity.setTime(currMsg.timestamp());
                Log.e(TAG, "" + currMsg.timestamp());
                entity.setType(currMsg.getConversation().getType());
                entity.setSenderName(currMsg.getSender());
                if (mUserNameMap.containsKey(currMsg.getSender())) {
//                    mUserNameMap.put(splitItems[0], splitItems[2]);
                    entity.setName(mUserNameMap.get(currMsg.getSender()));
                }
//                entity.setName(getName(currMsg.getSender()));
                entity.setStatus(currMsg.status());
                mArrayListChatEntity.add(entity);
            }
        }

        mChatMsgListAdapter.notifyDataSetChanged();
        mListViewMsgItems.setVisibility(View.VISIBLE);
        if (mListViewMsgItems.getCount() > 1) {
            if (mIsLoading)
                mListViewMsgItems.setSelection(0);
            else
                mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
//                mListViewMsgItems.setClickable(false);
        }
        mIsLoading = false;
    }
//
//    private String getName(String id){
//        if(mNormalMemberList != null && !TextUtils.isEmpty(id)){
//            for(MemberInfo member : mNormalMemberList){
//                if(id.equals(member.getUserPhone())){
//                    return member.getUserName();
//                }
//            }
//        }else{
//            return "";
//        }
//        return "";
//    }

    public boolean hideMsgIputKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null) {
                mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                return true;
            }
        }

        return false;
    }

    private void locateCameraPreview() {
        if (mDialogInit != null && mDialogInit.isShowing()) {
            mDialogInit.dismiss();
        }
    }

//    private AVEndpoint.RequestViewCompleteCallback mRequestViewCompleteCallback = new AVEndpoint.RequestViewCompleteCallback() {
//        protected void OnComplete(String identifier, int result) {
//            // TODO
//            Log.d(TAG, "RequestViewCompleteCallback.OnComplete");
//        }
//    };
//
//    private AVEndpoint.CancelViewCompleteCallback mCancelViewCompleteCallback = new AVEndpoint.CancelViewCompleteCallback() {
//        protected void OnComplete(String identifier, int result) {
//            // TODO
//            Log.d(TAG, "CancelViewCompleteCallback.OnComplete");
//        }
//    };

//    private boolean isFirst = true;

    public void hostRequestView(String identifier) {
        Log.d(TAG, "request " + identifier);

//        if(isFirst){
//            try{
//                Thread.sleep(1000);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//            isFirst = false;
//        }

        AVEndpoint endpoint = ((AVRoomMulti) mQavsdkControl.getAVContext().getRoom()).getEndpointById(identifier);
        Log.d(TAG, "hostRequestView identifier " + identifier + " endpoint " + endpoint);
        if (endpoint != null) {
            mVideoTimer = new Timer(true);
            mVideoTimerTask = new VideoTimerTask();
            mVideoTimer.schedule(mVideoTimerTask, 1000, 1000);
            AVView view = new AVView();
            view.videoSrcType = AVView.VIDEO_SRC_TYPE_CAMERA;//SDK1.2版本只支持摄像头视频源，所以当前只能设置为VIDEO_SRC_TYPE_CAMERA。
            view.viewSizeType = AVView.VIEW_SIZE_TYPE_BIG;

            //界面数
            mRequestViewList[0] = view;
            mRequestIdentifierList[0] = identifier;
            mRequestViewList[0].viewSizeType = AVView.VIEW_SIZE_TYPE_BIG;
            AVEndpoint.requestViewList(mRequestIdentifierList, mRequestViewList, 1, mRequestViewListCompleteCallback);
            //成员模式请求界面
            ctx.sendBroadcast(new Intent(Util.ACTION_VIDEO_SHOW)
                    .putExtra(Util.EXTRA_IDENTIFIER, identifier)
                    .putExtra(Util.EXTRA_VIDEO_SRC_TYPE, view.videoSrcType));//发送广播通知用户进入
        } else {
            mEditTextInputMsg.setVisibility(View.GONE);
            mButtonSendMsg.setVisibility(View.GONE);
//            mPraiseNum.setVisibility(View.GONE);
            mButtonPraise.setVisibility(View.GONE);

            dialog = new Dialog(this, R.style.dialog);
            dialog.setContentView(R.layout.alert_dialog);
            ((TextView) dialog.findViewById(R.id.dialog_title)).setText("温馨提示");
            ((TextView) dialog.findViewById(R.id.dialog_message)).setText("此直播已结束，请观看其他直播！");
            ((Button) dialog.findViewById(R.id.close_dialog)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onCloseVideo();
                    dialog.dismiss();
                }
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_btn:
                if (mRoomBean != null) {
                    final ShareRoomDialogFragment shareRoomDialogFragment = ShareRoomDialogFragment.newInstance(mRoomBean);
                    shareRoomDialogFragment.show(getSupportFragmentManager().beginTransaction(), "share_zhibo");
                }

                break;
            //跳转到人气
            case R.id.populator_layout:
                if (hostMember != null) {
                    Intent popularIntent = new Intent();
                    popularIntent.setClass(AvActivity.this, ContributionActivity.class);
                    popularIntent.putExtra(ContributionActivity.FLAG_USER_ID, hostMember.getUserPhone());
                    startActivity(popularIntent);
                }
                break;
            case R.id.qav_topbar_chat:
                mBottomInputBar.setVisibility(View.VISIBLE);
                mBottomToolBar.setVisibility(View.GONE);
                mEditTextInputMsg.requestFocus();
                KeyBoard(mEditTextInputMsg, true);
//                showKeyboard(mEditTextInputMsg);
                break;

            case R.id.black_place:
            case R.id.zan_layout:
                mBottomInputBar.setVisibility(View.GONE);
                mBottomToolBar.setVisibility(View.VISIBLE);
                mEmotionLayout.setVisibility(View.GONE);
                KeyBoard(mEditTextInputMsg, false);
//                hideKeyboard();
                break;

            case R.id.send_gift:
                if (Constants.sChooseId != Constants.NULL_POSITION) {
                    onSendGift();
                    mBottomInputBar.setVisibility(View.GONE);
                    mBottomToolBar.setVisibility(View.VISIBLE);
                    mEmotionLayout.setVisibility(View.GONE);
                }

                break;
            case R.id.gift_btn:
                mEmotionLayout.setVisibility(View.VISIBLE);
                mDiamondCount.setText(PreferencesStorageUtil.getDiamondCount(AvActivity.this) + "");
                mBottomInputBar.setVisibility(View.GONE);
                mBottomToolBar.setVisibility(View.GONE);
                break;
            case R.id.close:
            case R.id.qav_topbar_hangup:
                if (mIsSuccess && Constants.isCreater == false) {
                    memberCloseAlertDialog();
//                    onMemberExit();
//                    onCloseVideo();
                } else
                    hostCloseAlertDialog();
                break;
            case R.id.qav_topbar_switchcamera:
                onSwitchCamera();
                break;
            case R.id.qav_bottombar_send_msg:
                msgType = Constants.MESSAGETYPE.MESSAGE;//普通消息发送
                onSendMsg();
                break;
            case R.id.qav_bottombar_msg_input:
                mIsClicked = true;
                break;
            case R.id.image_btn_praise:
                mFavorLayout.addHeart();
//                mFavorLayout.addFavor();
                onSendPraise();
                break;
            case R.id.danmu_on_layout:
                //点击后关闭弹幕
                mDanmuOffLayout.setVisibility(View.VISIBLE);
                mDanmuOnLayout.setVisibility(View.GONE);
                mEditTextInputMsg.setHint("一起来聊一聊天");
                mIsDanmuOn = false;
                break;
            case R.id.danmu_off_layout:
                mDanmuOffLayout.setVisibility(View.GONE);
                mDanmuOnLayout.setVisibility(View.VISIBLE);
                mEditTextInputMsg.setHint("开启弹幕，10钻石/条");
                mIsDanmuOn = true;
                break;

            case R.id.pay_bottom_layout:
                Intent payIntent = new Intent();
                payIntent.setClass(AvActivity.this, MyDiamondActivity.class);
                startActivityForResult(payIntent, FLAG_PAY);
                break;

//            case R.id.qav_topbar_push:
//                Push();
////                Push();
//                break;

//            case R.id.qav_topbar_record:
////                Record();
//                if (!mRecord) {
//                    setRecordParam();
////                    startDefaultRecord();
//                } else {
//                    stopRecord();
//                }
//                break;
//            case R.id.btn_member_list:
//                showMemberList();
//                break;
            default:
                break;
        }
    }

    private void showKeyboard(EditText editText) {
        InputMethodManager inputMethodManager = (InputMethodManager)
                getSystemService(INPUT_METHOD_SERVICE);
// 接受软键盘输入的编辑文本或其它视图
        inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(AvActivity.this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static void KeyBoard(final EditText txtSearchKey, final boolean show) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager m = (InputMethodManager)
                        txtSearchKey.getContext().getSystemService(INPUT_METHOD_SERVICE);
                if (show) {
                    m.showSoftInput(txtSearchKey, InputMethodManager.SHOW_FORCED);
                } else {
                    m.hideSoftInputFromWindow(txtSearchKey.getWindowToken(), 0);
                }
            }
        }, 300);
    }


    public void showMemberList() {
//        if (Constants.isCreater == true) {
//            mMemberListDialog = new MemberListDialog(this, R.style.dialog, mNormalMemberList);
//            mMemberListDialog.freshRequestCount(mMemberVideoCount);
//            mMemberListDialog.show();
//        } else {
//            mMemberListDialog = new MemberListDialog(this, R.style.dialog, mNormalMemberList);
//            mMemberListDialog.show();
//        }
    }

    public void Push() {
        int roomid = (int) mQavsdkControl.getAVContext().getRoom().getRoomId();
        Log.i(TAG, "Push roomid: " + roomid);
        Log.d(TAG, "Push groupid: " + groupForPush);
//        Log.d(TAG, "Push enviroment: " + mSelfUserInfo.getEnv());

        TIMAvManager.RoomInfo roomInfo = TIMAvManager.getInstance().new RoomInfo();
        roomInfo.setRoomId(roomid);
        roomInfo.setRelationId(groupForPush);

        setParamAndPush(roomInfo);
    }


    private void stopPushAction(TIMAvManager.RoomInfo roomInfo) {
        List<Long> myList = new ArrayList<Long>();
        myList.add(streamChannelID);
        TIMAvManager.getInstance().requestMultiVideoStreamerStop(roomInfo, myList, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
            }
        });
    }

    private void pushAction(TIMAvManager.RoomInfo roominfo) {
        //推流的接口
        TIMAvManager.getInstance().requestMultiVideoStreamerStart(roominfo, mStreamParam, new TIMValueCallBack<TIMAvManager.StreamRes>() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "url error " + i + " : " + s);
                Toast.makeText(getApplicationContext(), "start stream error,try again " + i + " : " + s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(TIMAvManager.StreamRes streamRes) {
                List<TIMAvManager.LiveUrl> liveUrls = streamRes.getUrls();
                streamChannelID = streamRes.getChnlId();
                Log.e(TAG, liveUrls.toString());
                int length = liveUrls.size();
                String url = null;
                for (int i = 0; i < length; i++) {
                    TIMAvManager.LiveUrl avUrl = liveUrls.get(i);
                    url = avUrl.getUrl();
                    Log.e(TAG, "url success " + " : " + url);
                }
                streamVideoUrl = url;
                //往feed中添加一个直播item
                XLApplication.getInstance().getRestClient().putFeedInfo(roomNum + "", streamChannelID + "", streamVideoUrl, new Callback<RoomBean>() {
                    @Override
                    public void success(RoomBean roomBean, Response response) {
//                                toast(roomBean.getName() + "上传成功", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void failure(RetrofitError error) {
//                                toast("上传失败", Toast.LENGTH_SHORT);
                    }
                });
//                System.out.println("finalUrl---->" + finalUrl);
//
//                dialog = new Dialog(AvActivity.this, R.style.dialog);
//                dialog.setContentView(R.layout.alert_dialog);
//                ((TextView) dialog.findViewById(R.id.dialog_title)).setText("复制到粘贴板");
//                ((TextView) dialog.findViewById(R.id.dialog_message)).setText(url);
//                ((Button) dialog.findViewById(R.id.close_dialog)).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        ClipboardManager clip = (ClipboardManager) getApplicationContext().getSystemService(getApplicationContext().CLIPBOARD_SERVICE);
//                        clip.setText(finalUrl);
//                        dialog.dismiss();
//                        //Toast.makeText(getApplicationContext(), "copy success", Toast.LENGTH_SHORT).show();
//                    }
//                });
//                dialog.setCanceledOnTouchOutside(false);
//                dialog.show();

            }
        });
    }


    //    private EditText filenameEditText;
//    private EditText tagEditText;
//    private EditText classEditText;
//    private CheckBox trancodeCheckBox;
//    private CheckBox screenshotCheckBox;
//    private CheckBox watermarkCheckBox;
//    private String filename = "";
//    private String tags = "";
//    private String classId = "";
    TIMAvManager.RecordParam mRecordParam;
    TIMAvManager.StreamParam mStreamParam;

//
//    private void startDefaultRecord() {
//        Log.d(TAG, "setDefaultRecordParam roomName" + mQavsdkApplication.getRoomName());
//        mRecordParam = TIMAvManager.getInstance().new RecordParam();
//        mRecordParam.setFilename(mQavsdkApplication.getRoomName());
//        mRecordParam.setClassId(0);
//        mRecordParam.setTransCode(false);
//        mRecordParam.setSreenShot(false);
//        mRecordParam.setWaterMark(false);
//        mHandler.sendEmptyMessage(START_RECORD);
//    }

    public void startRecord() {
        mRecordParam = TIMAvManager.getInstance().new RecordParam();
        mRecordParam.setFilename(roomNum + "");
        mRecordParam.setClassId(1);
//        mHandler.sendEmptyMessage(START_RECORD);
//        startOrientationListener();

        int roomid = (int) mQavsdkControl.getAVContext().getRoom().getRoomId();
        Log.i(TAG, "roomid: " + roomid);
        Log.i(TAG, "groupid: " + groupForPush);

        TIMAvManager.RoomInfo roomInfo = TIMAvManager.getInstance().new RoomInfo();
        roomInfo.setRelationId(groupForPush);
        roomInfo.setRoomId(roomid);

        TIMAvManager.getInstance().requestMultiVideoRecorderStart(roomInfo, mRecordParam, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "Record error" + i + " : " + s);
//                Toast.makeText(getApplicationContext(), "start record error,try again", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess() {
                mRecord = true;
//                ((Button) findViewById(R.id.qav_topbar_record)).setTextColor(getResources().getColor(R.color.red));
//                ((Button) findViewById(R.id.qav_topbar_record)).setText("停录");
                Log.i(TAG, "begin to record");
//                Toast.makeText(getApplicationContext(), "start record now ", Toast.LENGTH_SHORT).show();
            }
        });

    }


    private void setParamAndPush(final TIMAvManager.RoomInfo roominfo) {
//        dialog = new Dialog(this, R.style.dialog);
//        dialog.setContentView(R.layout.push_param);
//        spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SDKtype);

        mStreamParam = TIMAvManager.getInstance().new StreamParam();
//        pushfileNameInput = (EditText) dialog.findViewById(R.id.push_filename);
//        pushfileNameInput.setText("" + mQavsdkApplication.getRoomName());
//        pushInfoInput = (EditText) dialog.findViewById(R.id.push_info);
////        pushCodeInput = (EditText) dialog.findViewById(R.id.push_password);
//        Button recordOk = (Button) dialog.findViewById(R.id.btn_record_ok);
        mStreamParam.setSdkType(TIMAvManager.SDKType.Normal);
        mStreamParam.setChannelName(roomNum + "");

        //设置默认值
        mStreamParam.setEncode(TIMAvManager.StreamEncode.HLS);
        pushAction(roominfo);

//        recordOk.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                if (pushfileNameInput.getText().toString().equals("")) {
//                    Toast.makeText(getApplicationContext(), "ChannelId can not be empty", Toast.LENGTH_LONG).show();
//                    return;
//                }
//
//                mStreamParam.setChannelName(pushfileNameInput.getText().toString());
////                mStreamParam.setChannelPasswd(pushCodeInput.getText().toString());
//                Log.d(TAG, "setParamAndPush " + StreamTypeCode);
//                switch (StreamTypeCode) {
//                    case Constants.FLV:
////                        mStreamParam.setEncode(TIMAvManager.StreamEncode.FLV);
//                        break;
//                    case Constants.HLS:
//                        mStreamParam.setEncode(TIMAvManager.StreamEncode.HLS);
//                        break;
//                    case Constants.RTMP:
//                        mStreamParam.setEncode(TIMAvManager.StreamEncode.RTMP);
//                        break;
//                    default:
//                        mStreamParam.setEncode(TIMAvManager.StreamEncode.HLS);
//                        break;
//                }
//                mStreamParam.setChannelDescr(pushInfoInput.getText().toString());
////                mStreamParam.setSdkType();
//
//
//                pushAction(roominfo);
//                startOrientationListener();
//                dialog.dismiss();
//            }
//        });
//        Button recordCancel = (Button) dialog.findViewById(R.id.btn_record_cancel);
//        recordCancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                startOrientationListener();
//                dialog.dismiss();
//            }
//        });
////        stopOrientationListener();
//        dialog.setCanceledOnTouchOutside(false);
//        dialog.show();
    }


    private void stopRecord() {
        try {
            final int roomid = (int) mQavsdkControl.getAVContext().getRoom().getRoomId();

            TIMAvManager.RoomInfo roomInfo = TIMAvManager.getInstance().new RoomInfo();
            roomInfo.setRelationId(groupForPush);
            roomInfo.setRoomId(roomid);
            TIMAvManager.getInstance().requestMultiVideoRecorderStop(roomInfo, new TIMValueCallBack<List<String>>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "stop record error " + i + " : " + s);
                    gotoGameOverActivity();
//                Toast.makeText(getApplicationContext(), "stop record error,try again", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onSuccess(List<String> files) {
                    mRecord = false;
                    for (String file : files) {
                        Log.d(TAG, "stopRecord onSuccess file  " + file);
                    }
                    videoRecordId = files.get(0);
//                uploadRecordToServer();
//                ((Button) findViewById(R.id.qav_topbar_record)).setTextColor(getResources().getColor(R.color.white));
//                ((Button) findViewById(R.id.qav_topbar_record)).setText("录制");
//                Toast.makeText(getApplicationContext(), "stop record success", Toast.LENGTH_SHORT).show();

                    XLApplication.getInstance().getRestClient().putFeedInfo(roomNum + "", (int) second, "", videoRecordId, "offline", new Callback<RoomBean>() {
                        @Override
                        public void success(RoomBean roomBean, Response response) {
                            gotoGameOverActivity();
//                                toast(roomBean.getName() + "上传成功", Toast.LENGTH_SHORT);
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            gotoGameOverActivity();
//                                toast("上传失败", Toast.LENGTH_SHORT);
                        }
                    });

                }
            });
            Log.d(TAG, "success");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void onCheckedChanged(boolean checked) {
        AVAudioCtrl avAudioCtrl = mQavsdkControl.getAVContext().getAudioCtrl();
        if (checked) {
            avAudioCtrl.enableMic(true);
        } else {
            Log.d(TAG, "audio Mic set false ");
            avAudioCtrl.enableMic(false);
        }
    }

    private boolean currentCameraIsFront = true;

    private void onSwitchCamera() {
        {
            boolean isFront = mQavsdkControl.getIsFrontCamera();
            Log.d(TAG, "onSwitchCamera 111111  " + isFront);

            mSwitchCameraErrorCode = mQavsdkControl.toggleSwitchCamera();
            Log.d(TAG, "onSwitchCamera() switchCamera!!  " + mSwitchCameraErrorCode);
            refreshCameraUI();
            if (mSwitchCameraErrorCode != AVError.AV_OK) {
                showDialog(isFront ? DIALOG_SWITCH_BACK_CAMERA_FAILED : DIALOG_SWITCH_FRONT_CAMERA_FAILED);
                mQavsdkControl.setIsInSwitchCamera(false);
                refreshCameraUI();
            } else {
//            Log.d(TAG, "onSwitchCamera " + currentCameraIsFront);
            }
        }
        boolean isFront = mQavsdkControl.getIsFrontCamera();
        Log.d(TAG, "onSwitchCamera 111111  " + isFront);

        mSwitchCameraErrorCode = mQavsdkControl.toggleSwitchCamera();
        Log.d(TAG, "onSwitchCamera() switchCamera!!  " + mSwitchCameraErrorCode);
        refreshCameraUI();
        if (mSwitchCameraErrorCode != AVError.AV_OK) {
            showDialog(isFront ? DIALOG_SWITCH_BACK_CAMERA_FAILED : DIALOG_SWITCH_FRONT_CAMERA_FAILED);
            mQavsdkControl.setIsInSwitchCamera(false);
            refreshCameraUI();
        } else {
//            Log.d(TAG, "onSwitchCamera " + currentCameraIsFront);
        }
    }

    private void onCloseVideo() {
//        if (mSelfUserInfo.isCreater() == true)
//            stopRecord();
//        stopOrientationListener();
//		showDialog(DIALOG_DESTROY);
        if (Constants.isCreater != true) {
            Util.switchWaitingDialog(ctx, mDialogAtDestroy, DIALOG_DESTROY, true);
        }
        if (mIsSuccess) {
            mChatTimer.cancel();
            mVideoTimer.cancel();
            timer.cancel();
            mHeartClickTimer.cancel();
        }
        //退出IM聊天室
        destroyTIM();
        //退出AV那边群
        mQavsdkControl.exitRoom();
        if (wakeLock.isHeld())
            wakeLock.release();
        if (Constants.isCreater == true) {
            closeLive();
            stopRecord();
//            stopPushAction();
            setResult(Util.SHOW_RESULT_CODE);
            Util.switchWaitingDialog(ctx, mDialogAtDestroy, DIALOG_DESTROY, true);
//            startActivity(new Intent(AvActivity.this, GameOverActivity.class)
//                    .putExtra(Util.EXTRA_ROOM_NUM, roomNum)
//                    .putExtra(Util.EXTRA_LEAVE_MODE,false)
//                    );
        } else {
            leaveLive();
            setResult(Util.VIEW_RESULT_CODE);
        }
//        startActivity(new Intent(AvActivity.this, GameOverActivity.class)
//                        .putExtra(Util.EXTRA_ROOM_NUM, roomNum)
//                        .putExtra(Util.EXTRA_USER_ID, mHostIdentifier)
//                        .putExtra(Util.EXTRA_LEAVE_MODE, LEVAE_MODE)
//        );
//        finish();
    }

    private void gotoGameOverActivity() {
        startActivity(new Intent(AvActivity.this, GameOverActivity.class)
                .putExtra(Util.EXTRA_ROOM_NUM, roomNum)
                .putExtra(Util.EXTRA_RECORDTIME, (int) second)
                .putExtra(Util.EXTRA_USER_ID, mHostIdentifier)
                .putExtra(Util.EXTRA_LEAVE_MODE, LEVAE_MODE)
        );
        finish();
    }

    //主播关闭房间
    private void closeLive() {

//XLApplication.getInstance().getRestClient().putFeedInfo();

        XLApplication.getInstance().getRestClient().putFeedInfo(roomNum + "", "offline", new Callback<RoomBean>() {
            @Override
            public void success(RoomBean nullResponse, Response response) {

            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
//
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    Log.d(TAG, "DEBUG " + mRecvIdentifier);
//                    object.put(Util.EXTRA_ROOM_NUM, roomNum);
//                    System.out.println(object.toString());
//                    List<NameValuePair> list = new ArrayList<NameValuePair>();
//                    list.add(new BasicNameValuePair("closedata", object.toString()));
//                    String ret = HttpUtil.PostUrl(HttpUtil.liveCloseUrl, list);
//                    Log.d(TAG, "close room" + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    //观众离开房间
    private void leaveLive() {
        XLApplication.getInstance().getRestClient().exitRoom(roomNum + "", new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                gotoGameOverActivity();
            }

            @Override
            public void failure(RetrofitError error) {
                gotoGameOverActivity();
            }
        });

//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_ROOM_NUM, roomNum);
//                    object.put(Util.EXTRA_USER_PHONE, mSelfUserInfo.getUserPhone());
//                    System.out.println(object.toString());
//                    List<NameValuePair> list = new ArrayList<NameValuePair>();
//                    list.add(new BasicNameValuePair("viewerout", object.toString()));
//                    String ret = HttpUtil.PostUrl(HttpUtil.closeLiveUrl, list);
//                    Log.d(TAG, "leave room" + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    private void onSendMsg() {
        final String msg = mEditTextInputMsg.getText().toString().trim();
        mEditTextInputMsg.setText("");

        //TODO 金币查询
        if (mIsDanmuOn) {
            onSendBarrage(msg);
        } else {
            if (msg.length() > 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendText(msg);
                    }
                }).start();
            }
        }
//        onSendBarrage(msg);
    }

    private void sendText(String msg) {
        if (msg.length() == 0)
            return;
        try {
            byte[] byte_num = msg.getBytes("utf8");
            if (byte_num.length > 160) {
                mHandler.sendEmptyMessage(ERROR_MESSAGE_TOO_LONG);
                return;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        TIMMessage mTIMMessage = new TIMMessage();//构造一条消息
        TIMTextElem elem = new TIMTextElem();//添加文本内容
        elem.setText(msg);
        if (mTIMMessage.addElement(elem) != 0) {
            return;
        }
        mConversation.sendMessage(mTIMMessage, new TIMValueCallBack<TIMMessage>() {//发送消息回调
            @Override
            public void onError(int i, String s) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code含义请参见错误码表
                if (i == 85) {
                    mHandler.sendEmptyMessage(ERROR_MESSAGE_TOO_LONG);
                } else if (i == 6011) {
                    mHandler.sendEmptyMessage(ERROR_ACCOUNT_NOT_EXIT);
                }
                Log.e(TAG, "send message failed. code: " + i + " errmsg: " + s);
//                getMessage();
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                Log.i(TAG, "Send text Msg ok");
                Message msg = new Message();
                msg.what = REFRESH_CHAT;
                msg.obj = timMessage;
                mHandler.sendMessage(msg);
//                showTextMessage(timMessage);
//                getMessage();
            }
        });
        sendCommentToServer(msg, false);
    }

    private void showTextMessage(TIMMessage timMessage) {
        Log.w(TAG, "showTextMessage ");
        TIMElem elem = timMessage.getElement(0);
        ChatEntity entity = new ChatEntity();
        entity.setElem(elem);
        entity.setIsSelf(timMessage.isSelf());
        Log.d(TAG, "showTextMessage  isSelf " + timMessage.isSelf());
        entity.setTime(timMessage.timestamp());
        entity.setType(timMessage.getConversation().getType());
        entity.setSenderName(timMessage.getSender());
        entity.setName(PreferencesStorageUtil.getUserBean(AvActivity.this).getNickname());
        entity.setStatus(timMessage.status());
        entity.setMsgType(msgType);
        mArrayListChatEntity.add(entity);
        mChatMsgListAdapter.notifyDataSetChanged();
        mListViewMsgItems.setVisibility(View.VISIBLE);
        if (mListViewMsgItems.getCount() > 1) {
            if (mIsLoading)
                mListViewMsgItems.setSelection(0);
            else
                mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
//                mListViewMsgItems.setClickable(false);
        }
    }

    private void showGifMessage(String userId, String sender, String msg) {
        Log.w(TAG, "showTextMessage ");
        ChatEntity entity = new ChatEntity();
        entity.setSenderName(userId);
        entity.setName(sender);
        entity.setMsg(msg);
        entity.setMsgType(msgType);
        mArrayListChatEntity.add(entity);
        mChatMsgListAdapter.notifyDataSetChanged();
        mListViewMsgItems.setVisibility(View.VISIBLE);
        if (mListViewMsgItems.getCount() > 1) {
            if (mIsLoading)
                mListViewMsgItems.setSelection(0);
            else
                mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
//                mListViewMsgItems.setClickable(false);
        }
    }

    //处理自定义消息
    private void handleCustomMsg(TIMElem elem) {
        Log.i(TAG, " inviteVC handleCustomMsg  ");
        try {
            String customText = new String(((TIMCustomElem) elem).getData(), "UTF-8");
            Log.i(TAG, " inviteVC handleCustomMsg  :" + customText);
            String splitItems[] = customText.split("&");
//            if(splitItems.length<=3){
//                splitItems[3]="";
//            }
            int cmd = Integer.parseInt(splitItems[1]);
            for (int i = 0; i < splitItems.length; ++i) {
                Log.d(TAG, " splitItems :" + splitItems[i] + " loop " + i);
            }
            switch (cmd) {
                case PRIASE_MSG:
                    int num = Integer.parseInt(splitItems[2]);
                    praiseNum += num;
                    if (mFavorLayout != null) {
                        mFavorLayout.addHeart();
//                        mFavorLayout.addFavor();
                    }
//                    mPraiseNum.setText("" + praiseNum);
                    break;

                case GIFT_SEND:
                    int giftId = Integer.parseInt(splitItems[2]);
                    String userId = splitItems[0];
                    if (mGiftList != null && mNormalMemberList != null) {
                        TIMGiftModel timGiftModel = new TIMGiftModel();
                        timGiftModel.setUserId(userId);
                        for (GiftBean giftBean : mGiftBeanList) {
                            if (giftBean.getId() == giftId) {
                                timGiftModel.setDesc("送了一个" + giftBean.getName());
                                timGiftModel.setGiftUrl(giftBean.getImage());
                                timGiftModel.setBig_image(giftBean.getBig_image());
                                timGiftModel.setDirection(giftBean.getDirection());
                                mPopulatorCount = mPopulatorCount + giftBean.getAmount();
                                mPopulatorText.setText(mPopulatorCount + "");
                            }
                        }

                        for (MemberInfo memberInfo : mNormalMemberList) {
                            if (memberInfo.getUserPhone().equals(userId)) {
                                timGiftModel.setHeadUrl(memberInfo.getHeadImagePath());
                                timGiftModel.setName(memberInfo.getUserName());
                            }
                        }
                        mGiftList.add(timGiftModel);
                        mHandler.sendEmptyMessage(SHOW_GIFT);
                    }

                    break;

                case BARRAGE_SEND:

                    mDanmu.toastText(1, splitItems[4], splitItems[2],
                            splitItems[3]);

//                    new Handler().postDelayed(this, 100);

//                    PreferencesStorageUtil.getUserId(AvActivity.this) + "&" + BARRAGE_SEND + "&" + msg + "&" + PreferencesStorageUtil.getUserBean(AvActivity.this).getAvatar() + "&" + PreferencesStorageUtil.getUserBean(AvActivity.this).getNickname();


//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            }
//                    }, 100);


                    break;
                //用户登录消息
                case MEMBER_ENTER_MSG:
                    boolean isExist = false;
                    //判断是否已经群组存在
                    for (int i = 0; i < mMemberList.size(); ++i) {

                        String userPhone = mMemberList.get(i).getUserPhone();
                        if (userPhone.equals(splitItems[0])) {
                            isExist = true;
                            Log.d(TAG, " willguo handleCustomMsg isExist = true  ");
                            break;
                        }
                    }
                    //不存在增加
                    if (!isExist) {
//                        Log.d(TAG, "willguo handleCustomMsg  isExist = false");
                        MemberInfo member;
                        //包含完整信息
                        if (splitItems.length <= 3) {
                            member = new MemberInfo(splitItems[0], splitItems[2], "");
                        } else {
                            member = new MemberInfo(splitItems[0], splitItems[2], splitItems[3]);
                        }

                        //cc 新登陆用户头像展示
                        synchronized (mMemberList) {
                            if (shownUserMap.size() < maxUserListSize) {
                                LayoutInflater layoutInflater = LayoutInflater.from(AvActivity.this);
                                View headItemView = layoutInflater.inflate(R.layout.layout_member_item, null);
                                CircularImageButton headImage = (CircularImageButton) headItemView.findViewById(R.id.head_image);
                                headImage.setTag(member);
                                Picasso.with(AvActivity.this).load(member.getHeadImagePath())
                                        .placeholder(R.drawable.channel_bg)
                                        .into(headImage);
                                mMemberScrollLayout.addView(headItemView, (int) (Math.random() * (shownUserMap.size())));
                                headImage.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        onMemberClick((MemberInfo) v.getTag());
                                    }
                                });
                                if (shownUserMap != null) {
                                    shownUserMap.put(member.getUserPhone(), member);
                                }
                            } else {
                                replaceRandomWithNew(member);
                            }
                        }
                        if (!mUserNameMap.containsKey(splitItems[0])) {
                            mUserNameMap.put(splitItems[0], splitItems[2]);
                        }
                        if (!member.getUserPhone().equals(PreferencesStorageUtil.getUserId(AvActivity.this))) {
                            mMemberList.add(member);
                            mNormalMemberList.add(member);
//                            m.setText("" + mMemberList.size());
                            mUserCountInteger++;
                            mUserCount.setText(mUserCountInteger + "");// + mMemberList.size());
                        }
//                        updateMemberHeadImage();
                        mHandler.sendEmptyMessage(UPDAT_MEMBER);
                    }
                    break;
                //用户登出消息
                case MEMBER_EXIT_MSG:
                    Log.d(TAG, "handleCustomMsg member leave userPhone splitItems" + splitItems[0]);
                    String userPhone;
                    for (int i = 0; i < mMemberList.size(); ++i) {
                        userPhone = mMemberList.get(i).getUserPhone();
                        Log.d(TAG, "handleCustomMsg member userPhone " + userPhone);
                        if (userPhone.equals(splitItems[0])) {
                            Log.d(TAG, "handleCustomMsg member leave userPhone " + userPhone);
//                            mQavsdkControl.closeMemberView(userPhone);
                            mMemberList.remove(i);
                            viewIndexRemove(userPhone);
                            MemberInfo normalMember = findMemberInfo(mNormalMemberList, userPhone);
                            mNormalMemberList.remove(normalMember);
                            if (mUserCountInteger > 0) {
                                mUserCountInteger--;
                            }
                            mUserCount.setText(mUserCountInteger + "");// + mMemberList.size());
                            mUserCount.setText("" + mMemberList.size());
//                            mMemberListButton.setText("" + mMemberList.size());

                        }
                    }
                    //cc 登出用户头像移除
                    synchronized (this) {
                        if (shownUserMap.containsKey(splitItems[0])) {
                            shownUserMap.remove(splitItems[0]);
                            try {
                                for (int i = 0; i < mMemberScrollLayout.getChildCount(); i++) {
                                    if (((MemberInfo) (mMemberScrollLayout.getChildAt(i).getTag())).getUserPhone().equals(splitItems[0])) {
                                        mMemberScrollLayout.removeViewAt(i);
                                    }
                                }
                            }catch(Exception e){e.printStackTrace();}
                        }
                        if (unShownUserMap.containsKey(splitItems[0])) {
                            unShownUserMap.remove(splitItems[0]);
                        }
                        if (shownUserMap.size() < minUserListSize) {
                            LayoutInflater layoutInflater = LayoutInflater.from(AvActivity.this);
                            View headItemView = layoutInflater.inflate(R.layout.layout_member_item, null);
                            CircularImageButton headImage = (CircularImageButton) headItemView.findViewById(R.id.head_image);
                            for (String key : unShownUserMap.keySet()) {
                                shownUserMap.put(key, shownUserMap.get(key));
                                unShownUserMap.remove(key);
                                Picasso.with(AvActivity.this).load(unShownUserMap.get(key).getHeadImagePath())
                                        .placeholder(R.drawable.channel_bg)
                                        .into(headImage);
                                headImage.setTag(unShownUserMap.get(key));
                                break;
                            }
                            mMemberScrollLayout.addView(headItemView, (int) (Math.random() * (shownUserMap.size())));
                            headImage.setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    onMemberClick((MemberInfo) v.getTag());
                                }
                            });
                        }
                    }

                    mHandler.sendEmptyMessage(UPDAT_MEMBER);
                    break;

                case MUTEVOICE:
                    AVAudioCtrl avAudioCtrl = mQavsdkControl.getAVContext().getAudioCtrl();
                    if (!OpenVoice) {
                        Toast.makeText(AvActivity.this, "host open your voice ", Toast.LENGTH_SHORT).show();
                        avAudioCtrl.enableMic(true);
                        OpenVoice = true;
                    } else {
                        Toast.makeText(AvActivity.this, "host close your voice ", Toast.LENGTH_SHORT).show();
                        avAudioCtrl.enableMic(false);
                        OpenVoice = false;
                    }
                    //关闭Mic
                    break;
                case UNMUTEVOICE:
                    Toast.makeText(AvActivity.this, "host allow your voice again ", Toast.LENGTH_SHORT).show();
                    //开启Mic
                    AVAudioCtrl avAudioCtrl2 = mQavsdkControl.getAVContext().getAudioCtrl();
                    avAudioCtrl2.enableMic(true);
                    break;
                case MUTEVIDEO:
                    if (!OpenVideo) {
                        //打开你的视频
                        Toast.makeText(AvActivity.this, "host open your camera  ", Toast.LENGTH_SHORT).show();
                        mQavsdkControl.toggleEnableCamera();
                        OpenVideo = true;
                    } else {
                        //关闭你的视频
                        Toast.makeText(AvActivity.this, "host close your camera ", Toast.LENGTH_SHORT).show();
                        mQavsdkControl.toggleEnableCamera();
                        OpenVideo = false;
                    }
                    break;
                case UNMUTEVIDEO:
                    Toast.makeText(AvActivity.this, "host allow your video again ", Toast.LENGTH_SHORT).show();
                    //开启Video
//                    if (mQavsdkControl.getIsInOnOffCamera() == false) {
                    mQavsdkControl.toggleEnableCamera();
//                    }
                    break;

                default:
                    break;
            }
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, " inviteVC handleCustomMsg  " + e.toString());
        }
    }

    //cc 头像随机替换展示
    private void replaceRandomWithNew(MemberInfo newMember) {
        synchronized (this) {
            LayoutInflater layoutInflater = LayoutInflater.from(AvActivity.this);
            View headItemView = layoutInflater.inflate(R.layout.layout_member_item, null);
            CircularImageButton headImage = (CircularImageButton) headItemView.findViewById(R.id.head_image);
            headImage.setTag(newMember);
            Picasso.with(AvActivity.this).load(newMember.getHeadImagePath())
                    .placeholder(R.drawable.channel_bg)
                    .into(headImage);

            int position = (int) (Math.random() * (shownUserMap.size()));
            shownUserMap.remove(((MemberInfo) (mMemberScrollLayout.getChildAt(position).getTag())).getUserPhone());
            mMemberScrollLayout.removeViewAt(position);
            mMemberScrollLayout.addView(headItemView, position);
            shownUserMap.put(newMember.getUserPhone(), newMember);
            headImage.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    onMemberClick((MemberInfo) v.getTag());
                }
            });
        }
    }


    private void initGiftView() {

        XLApplication.getInstance().getRestClient().getGifts(new Callback<GiftBean[]>() {
            @Override
            public void success(GiftBean[] giftBeans, Response response) {
                mGiftBeanList = new ArrayList<GiftBean>(Arrays.asList(giftBeans));
                mGiftAdapter = new GiftAdapter(getSupportFragmentManager(), mGiftBeanList);
                mEmotionVp.setAdapter(mGiftAdapter);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

    }

    public void onMemberClick(MemberInfo memberInfo) {
        MemberDialogFragment memberDialogFragment = MemberDialogFragment.newInstance(memberInfo);
        memberDialogFragment.show(getSupportFragmentManager().beginTransaction(), "show_member");
    }

    private void updateMemberView() {
//        if (mMemberListDialog != null)
//            mMemberListDialog.refreshMemberData(mNormalMemberList);

        //cc refreshMemberData(mNormalMemberList)
//        if(mMemberList!=null && mMemberList.size()>0) {
//            mMemberList.remove(0);
//        }
        LayoutInflater layoutInflater = LayoutInflater.from(AvActivity.this);
        if (mMemberList != null && mMemberList.size() > 0) {
            synchronized (this) {
                mMemberScrollLayout.removeAllViews();
                for (int i = 0; i < (maxUserListSize > mMemberList.size() ? mMemberList.size() : maxUserListSize); i++) {
                    View headItemView = layoutInflater.inflate(R.layout.layout_member_item, null);
                    CircularImageButton headImage = (CircularImageButton) headItemView.findViewById(R.id.head_image);
                    headImage.setTag(mMemberList.get(i));
                    mMemberScrollLayout.addView(headItemView);
                    toast("mMemberList.size():" + mMemberList.size(), 2);
                    Picasso.with(AvActivity.this).load(mMemberList.get(i).getHeadImagePath())
                            .placeholder(R.drawable.channel_bg)
                            .into(headImage);
                    headImage.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            onMemberClick((MemberInfo) v.getTag());
                        }
                    });
                    shownUserMap = new HashMap<>();
                    shownUserMap.put(mMemberList.get(i).getUserPhone(), mMemberList.get(i));
                }
                unShownUserMap = new HashMap<>();
                if (maxUserListSize < mMemberList.size()) {
                    for (int i = maxUserListSize; i < mMemberList.size(); i++) {
                        unShownUserMap.put(mMemberList.get(i).getUserPhone(), mMemberList.get(i));
                    }
                }
            }
        }

        mUserCount.setText("" + mMemberList.size());
        if (hostMember != null && !TextUtils.isEmpty(hostMember.getHeadImagePath())) {
            Picasso.with(AvActivity.this).load(hostMember.getHeadImagePath())
                    .placeholder(R.drawable.channel_bg)
                    .into(hostHead);
            hostHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //换成dialog

                    HostDialogFragment memberDialogFragment = HostDialogFragment.newInstance(hostMember);
                    memberDialogFragment.show(getSupportFragmentManager().beginTransaction(), "show_host");

//                    Intent viewHostIntent = new Intent();
//                    viewHostIntent.setClass(AvActivity.this, StarActivity.class);
//                    viewHostIntent.putExtra(StarActivity.USER_ID, hostMember.getUserPhone());
//                    startActivity(viewHostIntent);
                }
            });

//            imageLoader.displayImage(headurl, hostHead);
        }

    }

    //发送自定义消息
    private void onSendPraise() {
        String message = PreferencesStorageUtil.getUserId(AvActivity.this) + "&" + PRIASE_MSG + "&" + 1;
        TIMMessage Tim = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(message.getBytes());
        elem.setDesc(UNREAD);
        if (1 == Tim.addElement(elem))
            Toast.makeText(getApplicationContext(), "priase error", Toast.LENGTH_SHORT).show();
        else {
            mConversation.sendMessage(Tim, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "send praise error " + i + ": " + s);
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {
                    mHandler.sendEmptyMessage(REFRESH_PRAISE);
                    Log.i(TAG, "send priase success");
                }
            });
        }
        sendPraiseToServer();
    }


    private void sendPraiseToServer() {

        XLApplication.getInstance().getRestClient().postPraises(roomNum + "", new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {

            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }


    //TODO 发送礼物
    private void onSendGift() {

        //判断钻石数够不够
        int diamondCount = PreferencesStorageUtil.getDiamondCount(AvActivity.this);
        if (mGiftBeanList != null) {
            for (GiftBean giftBean : mGiftBeanList) {
                if (giftBean.getId() == Constants.sChooseId) {
                    if (giftBean.getAmount() > diamondCount) {//余额不足
                        RechargeFragment rechargeFragment = RechargeFragment.newInstance();
                        rechargeFragment.show(getSupportFragmentManager().beginTransaction(), "show_charge");
                        return;
                    }
                    mPopulatorCount = mPopulatorCount + giftBean.getAmount();
                    mPopulatorText.setText(mPopulatorCount + "");
                }
            }
        } else {
            return;
        }

        String message = PreferencesStorageUtil.getUserId(AvActivity.this) + "&" + GIFT_SEND + "&" + Constants.sChooseId;
        TIMMessage Tim = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(message.getBytes());
        elem.setDesc(UNREAD);
        if (1 == Tim.addElement(elem))
            Toast.makeText(getApplicationContext(), "priase error", Toast.LENGTH_SHORT).show();
        else {
            mConversation.sendMessage(Tim, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "send gift error " + i + ": " + s);
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {
//                    mHandler.sendEmptyMessage(REFRESH_PRAISE);
                    Log.i(TAG, "send gift success");
                }
            });
        }

        if (mGiftBeanList != null && mNormalMemberList != null) {
            TIMGiftModel timGiftModel = new TIMGiftModel();
            timGiftModel.setUserId(PreferencesStorageUtil.getUserId(AvActivity.this));
            for (GiftBean giftBean : mGiftBeanList) {
                if (giftBean.getId() == Constants.sChooseId) {
                    timGiftModel.setDesc("送了一个" + giftBean.getName());
                    timGiftModel.setGiftUrl(giftBean.getImage());
                    timGiftModel.setBig_image(giftBean.getBig_image());
                    timGiftModel.setDirection(giftBean.getDirection());
                }
            }
            timGiftModel.setHeadUrl(PreferencesStorageUtil.getUserBean(AvActivity.this).getAvatar());
            timGiftModel.setName(PreferencesStorageUtil.getUserBean(AvActivity.this).getNickname());
            mGiftList.add(timGiftModel);
            mHandler.sendEmptyMessage(SHOW_GIFT);
            msgType = Constants.MESSAGETYPE.GIFTMESSAGE;
//            sendText(timGiftModel.getDesc());
//            showGifMessage(timGiftModel.getName(),timGiftModel.getDesc());
        }

//        getMessage();
        sendGiftToServer();

    }

    private void sendGiftToServer() {

        XLApplication.getInstance().getRestClient().sendGift(roomNum + "", Constants.sChooseId + "", new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                //本地减少钻石数
                int diamondCount = PreferencesStorageUtil.getDiamondCount(AvActivity.this);
                if (mGiftBeanList != null) {
                    for (GiftBean giftBean : mGiftBeanList) {
                        if (giftBean.getId() == Constants.sChooseId) {
                            PreferencesStorageUtil.setDiamondCount(AvActivity.this, diamondCount - giftBean.getAmount());
                            mDiamondCount.setText(PreferencesStorageUtil.getDiamondCount(AvActivity.this) + "");
                        }
                    }
                }

                Constants.sChooseId = Constants.NULL_POSITION;
                if (mGiftAdapter != null) {
                    mGiftAdapter.refreshGiftList();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Constants.sChooseId = Constants.NULL_POSITION;
                if (mGiftAdapter != null) {
                    mGiftAdapter.refreshGiftList();
                }
            }
        });
    }

    //TODO 发送弹幕
    private void onSendBarrage(String msg) {
        //判断钻石数够不够
        int diamondCount = PreferencesStorageUtil.getDiamondCount(AvActivity.this);
        int danmuPrice = PreferencesStorageUtil.getDanmuPrice(AvActivity.this);
        if (mRoomBean != null) {
            danmuPrice = mRoomBean.getBarrage_amount();
        }
        if (danmuPrice > diamondCount) {
            RechargeFragment rechargeFragment = RechargeFragment.newInstance();
            rechargeFragment.show(getSupportFragmentManager().beginTransaction(), "show_charge");
            return;
        }

        String message = PreferencesStorageUtil.getUserId(AvActivity.this) + "&" + BARRAGE_SEND + "&" + msg + "&" + PreferencesStorageUtil.getUserBean(AvActivity.this).getAvatar() + "&" + PreferencesStorageUtil.getUserBean(AvActivity.this).getNickname();
        TIMMessage Tim = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(message.getBytes());
        elem.setDesc(UNREAD);
        if (1 == Tim.addElement(elem))
            Toast.makeText(getApplicationContext(), "priase error", Toast.LENGTH_SHORT).show();
        else {
            mConversation.sendMessage(Tim, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "send praise error " + i + ": " + s);
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {
                    mHandler.sendEmptyMessage(REFRESH_PRAISE);
                    Log.i(TAG, "send priase success");
                }
            });
        }

        mDanmu.toastText(1, PreferencesStorageUtil.getUserBean(AvActivity.this).getNickname(), msg,
                PreferencesStorageUtil.getUserBean(AvActivity.this).getAvatar());
//        getMessage();
        sendCommentToServer(msg, true);
    }

    //发送评论和发送弹幕是一起的
    private void sendCommentToServer(String msg, final boolean isBarrage) {

        XLApplication.getInstance().getRestClient().sendRoomComments(roomNum + "", msg, isBarrage, new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                if (isBarrage) {
                    //本地减少钻石数
                    int diamondCount = PreferencesStorageUtil.getDiamondCount(AvActivity.this);
                    PreferencesStorageUtil.setDiamondCount(AvActivity.this, diamondCount - PreferencesStorageUtil.getDanmuPrice(AvActivity.this));

                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }


//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_ROOM_NUM, roomNum);
//                    object.put("addnum", 1);
//                    System.out.println(object.toString());
//                    List<NameValuePair> list = new ArrayList<NameValuePair>();
//                    list.add(new BasicNameValuePair("praisedata", object.toString()));
//                    String ret = HttpUtil.PostUrl(HttpUtil.liveAddPraiseUrl, list);
//                    Log.e(TAG, "send praise to server return: " + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

    /**
     * 发一条消息告诉大家 自己上线了
     */
    private void onMemberEnter() {
//        mQavsdkApplication.enterPlusPlus();
//        if (mSelfUserInfo.getUserName() == null) {
//            mSelfUserInfo.setUserName("null");
//        }
//        if (mSelfUserInfo.getHeadImagePath().equals("")) {
//            mSelfUserInfo.setHeadImagePath("null");
//        }
//        String message = mSelfUserInfo.getUserPhone() + "&"
//                + MEMBER_ENTER_MSG + "&"
//                + mSelfUserInfo.getUserName() + "&"
//                + mSelfUserInfo.getHeadImagePath() + "&" + "inedex: " + mQavsdkApplication.getEnterIndex() + "&";

        if (TextUtils.isEmpty(UserUtils.getUserInstance().getNickname())) {
            UserUtils.getUserInstance().setNickname("null");
        }
        if (TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())) {
            UserUtils.getUserInstance().setAvatar("null");
        }
        String message = PreferencesStorageUtil.getUserId(this) + "&"
                + MEMBER_ENTER_MSG + "&"
                + UserUtils.getUserInstance().getNickname() + "&"
                + UserUtils.getUserInstance().getAvatar() + "&" + "inedex: " + mQavsdkApplication.getEnterIndex() + "&";


        Log.d(TAG, "onMemberEnter " + message);
        TIMMessage Tim = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(message.getBytes());
        elem.setDesc(UNREAD);
        if (1 == Tim.addElement(elem))
            Toast.makeText(getApplicationContext(), "enter error", Toast.LENGTH_SHORT).show();
        else {

            mConversation.sendMessage(Tim, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "enter error" + i + ": " + s);
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {
                    TIMCustomElem elem = (TIMCustomElem) (timMessage.getElement(0));
                    try {
                        String text = new String(elem.getData(), "utf-8");
                        Log.i(TAG, "msgSystem send groupmsg enter  success :" + text);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        final String msg = "轻轻地我来了";
        if (msg.length() > 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    msgType = Constants.MESSAGETYPE.MESSAGE;//普通消息发送
                    sendText(msg);
                }
            }).start();
        }
    }

    /**
     * 发一条消息通知大家 自己下线了
     */
    private void onMemberExit() {
        mQavsdkApplication.exitPlusPlus();
        String message = PreferencesStorageUtil.getUserId(AvActivity.this) + "&"
                + MEMBER_EXIT_MSG + "&" + "inedex: " + mQavsdkApplication.getExitIndex() + "&";
        ;
        TIMMessage Tim = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(message.getBytes());
        elem.setDesc(UNREAD);
        if (1 == Tim.addElement(elem))
            Toast.makeText(getApplicationContext(), "exit error", Toast.LENGTH_SHORT).show();
        else {
            mConversation.sendMessage(Tim, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "exit error" + i + ": " + s);

//                    mHandler.sendEmptyMessage(MEMBER_EXIT_COMPLETE);
                    mHandler.sendEmptyMessage(CLOSE_VIDEO);
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {

                    TIMCustomElem elem = (TIMCustomElem) (timMessage.getElement(0));
                    try {
                        String text = new String(elem.getData(), "utf-8");
                        Log.i(TAG, "msgSystem send groupmsg exit  success :" + text);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
//                    mHandler.sendEmptyMessage(MEMBER_EXIT_COMPLETE);
                    mHandler.sendEmptyMessage(CLOSE_VIDEO);
                }
            });
        }
        mMemberList.clear();
    }

    private void sendCloseMsg() {
        final String msg = "轻轻地离开了";
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (msg.length() == 0)
                    return;
                try {
                    byte[] byte_num = msg.getBytes("utf8");
                    if (byte_num.length > 160) {
                        mHandler.sendEmptyMessage(ERROR_MESSAGE_TOO_LONG);
                        return;
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return;
                }
                TIMMessage Nmsg = new TIMMessage();
                TIMTextElem elem = new TIMTextElem();
                elem.setText(msg);
                if (Nmsg.addElement(elem) != 0) {
                    return;
                }
                mConversation.sendMessage(Nmsg, new TIMValueCallBack<TIMMessage>() {
                    @Override
                    public void onError(int i, String s) {
                        if (i == 85) {
                            mHandler.sendEmptyMessage(ERROR_MESSAGE_TOO_LONG);
                        } else if (i == 6011) {
                            mHandler.sendEmptyMessage(ERROR_ACCOUNT_NOT_EXIT);
                        }
                        Log.e(TAG, "send message failed. code: " + i + " errmsg: " + s);
                        mHandler.sendEmptyMessage(CLOSE_VIDEO);
                    }

                    @Override
                    public void onSuccess(TIMMessage timMessage) {
                        Log.e(TAG, "Send text Msg ok");
                        mHandler.sendEmptyMessage(CLOSE_VIDEO);
                    }
                });
            }
        }).start();

    }

    //向用户服务器获取成员信息
    private void getMemberInfo() {
        XLApplication.getInstance().getRestClient().getRoomUsers(roomNum + "", "online", new Callback<UserBean[]>() {
            @Override
            public void success(UserBean[] userBeans, Response response) {
                try {
                    ZhiboUserListResponse zhiboUserListResponse = GsonUtil.fromJson(Util.inputStream2String(response.getBody().in()), ZhiboUserListResponse.class);
                    mUserCount.setText(zhiboUserListResponse.getTotal_count() + "");
                    mUserCountInteger = zhiboUserListResponse.getTotal_count();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {

                }

                mMemberList.clear();
                mNormalMemberList.clear();
                if (userBeans != null) {
                    for (UserBean userBean : userBeans) {
                        MemberInfo member = new MemberInfo(userBean.getId() + "", userBean.getNickname(), userBean.getAvatar(), userBean.getDescription());
                        mMemberList.add(member);
                        if (!mUserNameMap.containsKey(userBean.getId())) {
                            mUserNameMap.put(userBean.getId(), userBean.getNickname());
                        }
                    }
                    mNormalMemberList = copyToNormalMember();
                }
                mHandler.sendEmptyMessage(UPDAT_MEMBER);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;

        switch (id) {
//            case DIALOG_INIT:
//                dialog = mDialogInit = Util.newProgressDialog(this, R.string.interface_initialization);
//                break;
//            case DIALOG_AT_ON_CAMERA:
//                dialog = mDialogAtOnCamera = Util.newProgressDialog(this, R.string.at_on_camera);
//                break;
            case DIALOG_ON_CAMERA_FAILED:
                dialog = Util.newErrorDialog(this, R.string.on_camera_failed);
                break;
            case DIALOG_AT_OFF_CAMERA:
                dialog = mDialogAtOffCamera = Util.newProgressDialog(this, R.string.at_off_camera);
                break;
            case DIALOG_OFF_CAMERA_FAILED:
                dialog = Util.newErrorDialog(this, R.string.off_camera_failed);
                break;

//            case DIALOG_AT_SWITCH_FRONT_CAMERA:
//                dialog = mDialogAtSwitchFrontCamera = Util.newProgressDialog(this, R.string.at_switch_front_camera);
//                break;
//            case DIALOG_SWITCH_FRONT_CAMERA_FAILED:
//                dialog = Util.newErrorDialog(this, R.string.switch_front_camera_failed);
//                break;
//            case DIALOG_AT_SWITCH_BACK_CAMERA:
//                dialog = mDialogAtSwitchBackCamera = Util.newProgressDialog(this, R.string.at_switch_back_camera);
//                break;
//            case DIALOG_SWITCH_BACK_CAMERA_FAILED:
//                dialog = Util.newErrorDialog(this, R.string.switch_back_camera_failed);
//                break;
            case DIALOG_DESTROY:
                dialog = mDialogAtDestroy = Util.newProgressDialog(this, R.string.at_close_room);
                break;
            default:
                break;
        }
        return dialog;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DIALOG_ON_CAMERA_FAILED:
            case DIALOG_OFF_CAMERA_FAILED:
                ((AlertDialog) dialog).setMessage(getString(R.string.error_code_prefix) + mOnOffCameraErrorCode);
                break;
            case DIALOG_SWITCH_FRONT_CAMERA_FAILED:
            case DIALOG_SWITCH_BACK_CAMERA_FAILED:
                ((AlertDialog) dialog).setMessage(getString(R.string.error_code_prefix) + mSwitchCameraErrorCode);
                break;
            default:
                break;
        }
    }

    private void refreshCameraUI() {
        boolean isEnable = mQavsdkControl.getIsEnableCamera();
        boolean isFront = mQavsdkControl.getIsFrontCamera();
        boolean isInOnOffCamera = mQavsdkControl.getIsInOnOffCamera();
        boolean isInSwitchCamera = mQavsdkControl.getIsInSwitchCamera();


        if (isInOnOffCamera) {
            if (isEnable) {

                Util.switchWaitingDialog(this, mDialogAtOffCamera, DIALOG_AT_OFF_CAMERA, true);
                Util.switchWaitingDialog(this, mDialogAtOnCamera, DIALOG_AT_ON_CAMERA, false);
            } else {
                Util.switchWaitingDialog(this, mDialogAtOffCamera, DIALOG_AT_OFF_CAMERA, false);
//                Util.switchWaitingDialog(this, mDialogAtOnCamera, DIALOG_AT_ON_CAMERA, true);
                Util.switchWaitingDialog(this, mDialogAtOnCamera, DIALOG_AT_ON_CAMERA, false);

            }
        } else {
            Util.switchWaitingDialog(this, mDialogAtOffCamera, DIALOG_AT_OFF_CAMERA, false);
            Util.switchWaitingDialog(this, mDialogAtOnCamera, DIALOG_AT_ON_CAMERA, false);
        }

        if (isInSwitchCamera) {
            if (isFront) {
                Util.switchWaitingDialog(this, mDialogAtSwitchBackCamera, DIALOG_AT_SWITCH_BACK_CAMERA, true);
                Util.switchWaitingDialog(this, mDialogAtSwitchFrontCamera, DIALOG_AT_SWITCH_FRONT_CAMERA, false);
            } else {
                Util.switchWaitingDialog(this, mDialogAtSwitchBackCamera, DIALOG_AT_SWITCH_BACK_CAMERA, false);
                Util.switchWaitingDialog(this, mDialogAtSwitchFrontCamera, DIALOG_AT_SWITCH_FRONT_CAMERA, true);
            }
        } else {
            Util.switchWaitingDialog(this, mDialogAtSwitchBackCamera, DIALOG_AT_SWITCH_BACK_CAMERA, false);
            Util.switchWaitingDialog(this, mDialogAtSwitchFrontCamera, DIALOG_AT_SWITCH_FRONT_CAMERA, false);
        }
    }

    private void updateWallTime() {
        String formatTime;
        String hs, ms, ss;

        long h, m, s;
        h = second / 3600;
        m = (second % 3600) / 60;
        s = (second % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }

        formatTime = hs + ":" + ms + ":" + ss;
        mClockTextView.setText(formatTime);
    }


    private Dialog dialog;

    private void hostCloseAlertDialog() {
        dialog = new Dialog(this, R.style.dialog);
        dialog.setContentView(R.layout.exit_dialog);
        TextView messageTextView = (TextView) dialog.findViewById(R.id.message);
        Button exitOk = (Button) dialog.findViewById(R.id.btn_exit_ok);
        Button exitCancel = (Button) dialog.findViewById(R.id.btn_exit_cancel);
        messageTextView.setText("有" + mMemberList.size() + "人正在看您的直播\n确定结束直播吗？");
        exitOk.setText("结束直播");
        exitCancel.setText("继续直播");
        exitOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                onCloseVideo();
                dialog.dismiss();
            }
        });

        exitCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startOrientationListener();
                dialog.dismiss();
            }
        });
//        stopOrientationListener();
        dialog.show();
    }

    private void memberCloseAlertDialog() {
        dialog = new Dialog(this, R.style.dialog);
        dialog.setContentView(R.layout.exit_dialog);
        TextView messageTextView = (TextView) dialog.findViewById(R.id.message);
        Button exitOk = (Button) dialog.findViewById(R.id.btn_exit_ok);
        Button exitCancel = (Button) dialog.findViewById(R.id.btn_exit_cancel);
        messageTextView.setText("确认退出吗？");
        exitOk.setText("结束观看");
        exitCancel.setText("继续观看");
        exitOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                onMemberExit();
                dialog.dismiss();
            }
        });

        exitCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startOrientationListener();
                dialog.dismiss();
            }
        });
//        stopOrientationListener();
        dialog.show();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mIsClicked) {
                    mIsClicked = false;
                    break;
                }
                if (Constants.isCreater)
                    hostCloseAlertDialog();
                else {
                    memberCloseAlertDialog();
//                    onCloseVideo();
                }
                break;
        }

        return false; //这一句很关键
    }

    private boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(TAG)) {
            isTop = true;
        }
        return isTop;
    }


    private static final int TIMER_INTERVAL = 1000;
    private boolean showTips = false;
    Timer timer = new Timer();
//    TimerTask task = new TimerTask() {
//        public void run() {
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    if (showTips) {
//                        if (tvTipsMsg != null) {
//                            String strTips = mQavsdkControl.getQualityTips();
//                            strTips = praseString(strTips);
//                            if (!TextUtils.isEmpty(strTips)) {
//                                tvTipsMsg.setText(strTips);
//                            }
//                        }
//                    } else {
//                        tvTipsMsg.setText("");
//                    }
//                }
//            });
//        }
//    };

    private String praseString(String video) {
        if (video.length() == 0) {
            return "";
        }
        String result = "";
        String splitItems[];
        String tokens[];
        splitItems = video.split("\\n");
        for (int i = 0; i < splitItems.length; ++i) {
            if (splitItems[i].length() < 2)
                continue;

            tokens = splitItems[i].split(":");
            if (tokens[0].length() == "mainVideoSendSmallViewQua".length()) {
                continue;
            }
            if (tokens[0].endsWith("BigViewQua")) {
                tokens[0] = "mainVideoSendViewQua";
            }
            if (tokens[0].endsWith("BigViewQos")) {
                tokens[0] = "mainVideoSendViewQos";
            }
            result += tokens[0] + ":\n" + "\t\t";
            for (int j = 1; j < tokens.length; ++j)
                result += tokens[j];
            result += "\n\n";
            //Log.d(TAG, "test:" + result);
        }
        //Log.d(TAG, "test:" + result);
        return result;
    }


    private void heartClick() {
        Log.d(TAG, "heartClick click ");
//        JSONObject object = new JSONObject();
//        try {
//            object.put(Util.EXTRA_LIVEPHONE, mSelfUserInfo.getUserPhone());
//            List<NameValuePair> list = new ArrayList<NameValuePair>();
//            list.add(new BasicNameValuePair("heartTime", object.toString()));
//            String ret = HttpUtil.PostUrl(HttpUtil.heartClickUrl, list);
//            Log.d(TAG, "hear click" + ret);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        XLApplication.getInstance().getRestClient().postHeartClick(roomNum + "", new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                //心跳成功
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

    }

    private AVEndpoint.RequestViewListCompleteCallback mRequestViewListCompleteCallback = new AVEndpoint.RequestViewListCompleteCallback() {
        protected void OnComplete(String identifierList[], int count, int result) {
            // TODO
            Log.d(TAG, "RequestViewListCompleteCallback.OnComplete");
        }
    };


    private String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }

    public MemberInfo findMemberInfo(ArrayList<MemberInfo> list, String id) {
        Log.d(TAG, "findMemberInfo id" + id);
        String identifier = id;
        for (MemberInfo member : list) {

            if (member.getUserPhone().equals(identifier))
                return member;
        }
        return null;
    }

//    public void downMemberLevel(String identifier) {
//        MemberInfo upMember = findMemberInfo(mVideoMemberList, identifier);
//        mNormalMemberList.add(upMember);
//        mVideoMemberList.remove(upMember);
//        mMemberListDialog.refreshMemberData(mNormalMemberList, mVideoMemberList);
//    }

    public ArrayList<MemberInfo> copyToNormalMember() {
        mNormalMemberList = new ArrayList<MemberInfo>();
        for (MemberInfo member : mMemberList) {
            if (hostMember != null && !hostMember.getUserPhone().equals(member.getUserPhone()))
                mNormalMemberList.add(member);
        }
        return mNormalMemberList;
    }

//    private void closeVideoMemberByHost(String identifer) {
//        viewIndexRemove(identifer);
//        sendCloseVideoMsg(identifer);
//        mQavsdkControl.closeMemberView(identifer);
//        downMemberLevel(identifer);
//    }

    private void viewIndexRemove(String identifer) {
        if (viewIndex != null) {
            String id;
            if (identifer.startsWith("86-")) {
                id = identifer.substring(3);

            } else {
                id = identifer;
            }
            if (viewIndex.containsKey(id)) {
                viewIndex.remove(id);
            }
        }
    }

    private class GifTask {
        GifTask(String des, String url, String type) {
            this.des = des;
            this.url = url;
            this.type = type;
        }

        String des;
        String url;
        String type;
    }
}